首先 只有String才與編碼有關;
byte與其他類型轉換時,要注意大端點還是小端點,
編碼: Ascii Unicode gbk utf-8等等
byte 占 8位 可由兩個16進位數(0xff)組成,一個16進位佔4位,也可由8位位元組成等等,與編碼沒關係,但可用2進位表示,也可由其他進位表示。
“0xff”這樣的16進位字串轉換成16進位byte
String[] s="0X0C 0X03 0X00 0X04 0X00 0X02 0X84 0XD7".replace("X", "x").split(" ");byte[] b=new byte[s.length];for(int i=0;i<s.length;i++){b[i]=(byte)Integer.parseInt(s[i].substring(2),16);}System.out.println(Arrays.toString(b));
把byte[n]轉換成String;
new String(byte[n],0,length,"gbk");
float占 4位元組 ,float與byte類型轉換
都是通過移位來實現的
4byte轉換成float
左移位
/**
* 位元組轉換為浮點
*
* @param b 位元組(至少4個位元組)
* @param index 開始位置
* @return
*/
public static float byte2float(byte[] b, int index) {
int l;
l = b[index + 0];
l &= 0xff;
l |= ((long) b[index + 1] << 8);
l &= 0xffff;
l |= ((long) b[index + 2] << 16);
l &= 0xffffff;
l |= ((long) b[index + 3] << 24);
return Float.intBitsToFloat(l);
}
float轉換成4byte
右移位 /**
* 浮點轉換為位元組
*
* @param f
* @return
*/
public static byte[] float2byte(float f) {
// 把float轉換為byte[]
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}
// 翻轉數組
int len = b.length;
// 建立一個與源數組元素類型相同的數組
byte[] dest = new byte[len];
// 為了防止修改源數組,將源數組拷貝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 將順位第i個與倒數第i個交換
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
return dest;
}