// 字节转成UCHAR型,由于Java不支持UCHAR类型,所以这里转换成short类型
public static short byte2Uchar(byte[] b, int off) {
int temp = b[0];
if (b[0] < 0) {
temp = temp + 256;
}
return (short) temp;
}
// 字节转成short型
public static short byte2Short(byte[] b, int off) {
return (short) (((b[off + 1] & 0xFF) << 0) + ((b[off + 0] & 0xFF) << 8));
}
// 字节转成int型
public static int byte2Int(byte[] b, int off) {
return ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8)
+ ((b[off + 1] & 0xFF) << 16) + ((b[off + 0] & 0xFF) << 24);
}
// 字节转成long型
public static long byte2Long(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8)
+ ((b[off + 5] & 0xFFL) << 16) + ((b[off + 4] & 0xFFL) << 24)
+ ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40)
+ ((b[off + 1] & 0xFFL) << 48) + ((b[off + 0] & 0xFFL) << 56);
}
// 字节转成float型
public static float byte2Float(byte[] b, int off) {
int i = ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8)
+ ((b[off + 1] & 0xFF) << 16) + ((b[off + 0] & 0xFF) << 24);
return Float.intBitsToFloat(i);
}
// 字节转成double型
public static double byte2Double(byte[] b, int off) {
long j = ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8)
+ ((b[off + 5] & 0xFFL) << 16) + ((b[off + 4] & 0xFFL) << 24)
+ ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40)
+ ((b[off + 1] & 0xFFL) << 48) + ((b[off + 0] & 0xFFL) << 56);
return Double.longBitsToDouble(j);
}
// 字节转成char型
public static char byte2Char(byte[] b, int off) {
return (char) (((b[off + 1] & 0xFF) << 0) + ((b[off + 0] & 0xFF) << 8));
}
// 长整型转成字节
public static byte[] longToByte(long number) {
long temp = number;
byte[] b = new byte[8];
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}
String charsetName = "UTF-8";
String stringContent = "Test";
String string = new String(stringContent);
byte[] bytes = new byte[0];
try {
// 字符串转字节
bytes = string.getBytes(charsetName);
System.out.println(bytes);
for(byte b : bytes){
System.out.println(b);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
// 字节转字符串
String newString = new String(bytes, charsetName);
System.out.println(newString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
当然,借助java.io里的CharBuffer、IntBuffer等,也是一种选择,可参考:https://blog.csdn.net/nie_feilong/article/details/5784595