java字符串轉(zhuǎn)byte delphi中BYTE數(shù)組和String之間怎樣相互轉(zhuǎn)換?
delphi中BYTE數(shù)組和String之間怎樣相互轉(zhuǎn)換?vararrbyte:字節(jié)數(shù)組[0..2]str1:字符串i:整數(shù)begin對于i:=0 to Length(arrbyte)-1 dostr
delphi中BYTE數(shù)組和String之間怎樣相互轉(zhuǎn)換?
var
arrbyte:字節(jié)數(shù)組[0..2]
str1:字符串
i:整數(shù)
begin
對于i:=0 to Length(arrbyte)-1 do
str:=str IntToStr(arrbyte[i])//Byte[]to string
對于i:=0 to Length(str)-1 do
arrbyte[i]:=Byte(str[i])//字符串到字節(jié)[
]StrCopy(PChar(@arrbyte),PChar(str))//字符串到字節(jié)[
]end
怎樣將Byte轉(zhuǎn)換成字符串?
有兩種方法:
方法1:
//string to byte
string stringmessage=“你好嗎?"
控制臺寫入線(“{0}”,StringMessage)System.Text.ASCIIEncoding系統(tǒng)ASCII=新System.Text.ASCIIEncoding系統(tǒng)()
字節(jié)[]字節(jié)消息=ASCII.GetBytes(stringmessage)
//字節(jié)到字符串
字節(jié)[]字節(jié)消息System.Text.ASCIIEncoding系統(tǒng)ASCII=新System.Text.ASCIIEncoding系統(tǒng)()
字符串消息=ASCII.GetString(bytesmessage)
方法2:
//string to UTF-8 byte
string stringmessage=“你好,你好嗎?Pi/u03c0日元/uffe5“System.Text.utf8編碼UTF8=新System.Text.utf8編碼()
byte[]bytesmessage=utf8。GetBytes(stringmessage)
//UTF-8字節(jié)到字符串
byte[]BytesMessageSystem.Text.utf8編碼UTF8=新System.Text.utf8編碼()
string stringmessage=utf8。GetString(bytesmessage)
delphi中怎樣把string轉(zhuǎn)為arrayofbyte?
下面是示例代碼:
過程TForm1。Button1click(sender:tobject)var s:String AB:byte數(shù)組I:integerbegin s:=“this is a test”setlength(AB,length(s))for I:=1 to length(s)do AB[I]:=byte(s[I])end
在Java中,可以直接使用String類的構(gòu)造函數(shù)將byte數(shù)組轉(zhuǎn)換成字符串。要將字符串轉(zhuǎn)換為字節(jié)數(shù)組,可以使用字符串類型的getbytes()方法進行轉(zhuǎn)換,如下所示:
1。字符串到字節(jié)[
String STR=“Hello”//聲明字符串
byte[]srtbyte=字符串getBytes()//使用string類的GetBytes方法進行轉(zhuǎn)換
2。將byte[]轉(zhuǎn)換為字符串
byte[]srtbyte//聲明字節(jié)數(shù)組
string res=New string(srtbyte)//使用構(gòu)造函數(shù)轉(zhuǎn)換為字符串系統(tǒng)輸出打?。≧ES)
您還可以設(shè)置編碼模式,以便在轉(zhuǎn)換字節(jié)時相互轉(zhuǎn)換,如下所示:
string STR=“Hello”
byte[]srtbyte=null試試{
srtbyte=字符串getBytes(“UTF-8”)//設(shè)置轉(zhuǎn)換的編碼格式
string res=New string(srtbyte,“UTF-8”)系統(tǒng)輸出打?。≧ES)
}catch(不支持的編碼異常E){//可能存在不支持的編碼格式和catch異常。
e.printStackTrace()
}