位元組數組與字串(字元數組)的轉換操作,位元組數組
1、預設編碼方式轉換:
(1)string(char[])轉換為byte[]
byte[] byteArr = System.Text.Encoding.Default.GetBytes(char[]);byte[] byteArr = System.Text.Encoding.Default.GetBytes(string);byte[] byteArr = System.Text.Encoding.Default.GetBytes(char[], startindex, count);int count = System.Text.Encoding.Default.GetBytes(char * , count, byte*, startindex);int count = System.Text.Encoding.Default.GetBytes(char[] , startindex, count, byte[], startindex);int count = System.Text.Encoding.Default.GetBytes(s , startindex, count, byte[], startindex);
(2)byte[]轉換為string(char[])
string str = System.Text.Encoding.Default.GetString ( byteArray );string str = System.Text.Encoding.Default.GetString ( byteArray, startindex, count );
GetString方法和GetChar方法類似,後者將位元組數群組轉換為對應的字元數組。
2、其他編碼方式轉換
將上述Default更換為ASCII、Unicode、UTF8、UTF7、UTF32等編碼方式,然後調用對應方法就可以轉換。
string str = "01";byte[] byteArr = System.Text.Encoding.ASCI.GetBytes(str);
上述代碼得到byteArr = {0x30, 0x31},這就是0和1的ASCI編碼值。
byte[] byteArr = new byte[]{0x4e, 0x01};string a = System.Text.Encoding.BigEndianUnicode.GetString(byteArr);上述代碼將unicode編碼的第二個漢字“丁”解碼賦值給變數a,“丁”的unicode碼為\u4e01。
3、Byte[]中的十六進位轉換為十六進位字串
public static string ToHexString ( byte[] bytes ) { string hexString = string.Empty; if ( bytes != null ) { StringBuilder strB = new StringBuilder (); for ( int i = 0; i < bytes.Length; i++ ) { strB.Append ( bytes[i].ToString ( "X2" ) ); } hexString = strB.ToString (); } return hexString; }
4、十六進位字串轉換為Byte數組
public static byte[] GetBytes(string hexString, out int discarded) { discarded = 0; string newString = ""; char c; // remove all none A-F, 0-9, characters for (int i=0; i<hexstring.length; i++) { c = hexString[i]; if (IsHexDigit(c)) newString += c; else discarded++; } // if odd number of characters, discard last character if (newString.Length % 2 != 0) { discarded++; newString = newString.Substring(0, newString.Length-1); } int byteLength = newString.Length / 2; byte[] bytes = new byte[byteLength]; string hex; int j = 0; for (int i=0; i<bytes.length; i++) { hex = new String(new Char[] {newString[j], newString[j+1]}); bytes[i] = HexToByte(hex); j = j+2; } return bytes; } 對於擷取到的使用unicode編碼的網頁或者其他檔案,可以使用上述方法將加密後的unicode編碼字串轉換為byte數組,然後再使用前面提到的轉換方法轉換為對應的字元。
java中怎將byte數組內容轉換為字串?
public class ByteTest {
public static void main(String[] args) {
String str = "Hello world!";
// string轉byte
byte[] bs = str.getBytes();
System.out.println(Arrays.toString(bs));
// byte轉string
String str2 = new String(bs);
System.out.println(str2);
}
}
labview中有字串到位元組數群組轉換,有沒有字串到字(16位)數組的轉換?,我要讓他采個16位的資料
三位,看圖吧。其中U16常數陣列隱藏了索引框。字串和數值都是用十六進位顯示的,方便查看。“從字串還原函數”使用big-endian還是little-endian可選。