java 裡面的string 和byte 互轉

2021-07-06 00:13:42 字數 1412 閱讀 6641

1.string 轉 byte

byte midbytes=isostring.getbytes("utf8");

//為utf8編碼

byte isoret = srt2.getbytes("iso-8859-1");

//為iso-8859-1編碼

其中iso-8859-1為單位元組的編碼

2.byte轉string

string isostring = new string(bytes,"iso-8859-1");

string srt2=new string(midbytes,"utf-8");

說明:在網路傳輸或其它應用中常常有同一的中介軟體,假設為string型別。因此需要把其它型別的資料轉換為中介軟體的型別。

將字串進行網路傳輸時,如socket,需要將其在轉換為byte型別。這中間如果採用用不同的編碼可能會出現未成預料的問題,如亂碼。

下面舉個例子:

我們用socket傳輸string型別的資料時,常常用utf-8進行編碼,這樣比較可以避免乙個「中文亂碼」的問題。

傳送端:

string sendstring="傳送資料";

byte sendbytes= sendstring .getbytes("utf8");

.......socket傳送

接受端:

string recstring=new string( sendbytes ,"utf-8");

但是,這裡往往又會出現這樣乙個問題。就是想要傳送的資料本身就是byte型別的。

如果將其通過utf-8編碼轉換為中介軟體string型別就會出現問題

如:byte bytes = new byte ;

string sendstring=new string( bytes ,"utf-8");

byte sendbytes= sendstring .getbytes("utf8");

然後再傳送

接受時進行逆向轉換

string recstring=new string( sendbytes ,"utf-8");

byte mybytes=isostring.getbytes("utf8");

這時mybytes中的資料將是[50, 0, -17, -65, -67, 28, -17, -65, -67]

因此,需要採用單位元組的編碼方式進行轉換

string sendstring=new string( bytes ,"utf-8"); 改為 string sendstring=new string( bytes , "iso-8859-1" );

byte mybytes=isostring.getbytes("utf8"); 改為 byte mybytes=isostring.getbytes( "iso-8859-1" );

這樣所需要的位元組就有恢復了。

關於boost裡面的string

include 首先是盤點子串是否是父串的乙個子串。如下所示 std string str i don t know.n std cout to upper copy std cout boost to lower str std cout std string str power bomb if ...

C 裡String裡面的find

tolower 就是轉換為小寫 toupper就是轉換為大寫 例子如下 include include include using namespace std int main string裡面find的用法 a.find 查詢第一次出現的目標字串 include include include u...

jquery裡面的 this 和this

當你用的是jquery時,就用 this 如果是js,就用this this html this html bam 這個裡的html 是jquery方法,用 this html 當然,js裡也有相似方法innerhtml,如果用innerhtml,就要這樣寫了,這裡的reset是js方法,所以同上得...