Java 中基本类型都是有符号数值,如果接收到了 C/C++ 处理的无符号数值字节流,将出现转码错误。
提示:以下是本篇文章正文内容,下面案例可供参考
在线进制转换:https://tool.oschina.net/hexconvert
之前在解析 webscoket 传输得二进制数据时,因为二进制数据传输的是 uint32 无符号整数,需要把有符号的字节转为正常的;
uint32 代表无符号整数,只能存正整数,在内存中占4个字节,byte[4],0到4294967295,Java中 int 为32位有符号整数,占4字节,-2147483648 到 2147483648。
public static long bytes2int(byte[] buf){
long anUnsignedInt = 0;
int firstByte = 0;
int sceondByte = 0;
int thirdByte = 0;
int fourthByte = 0;
int index = 0;
firstByte = (0x000000FF & ((int) buf[index+3]));
sceondByte = (0x000000FF & ((int) buf[index+2]));
thirdByte = (0x000000FF & ((int) buf[index+1]));
fourthByte = (0x000000FF & ((int) buf[index]));
anUnsignedInt = ((long) (firstByte << 24 | sceondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;
return anUnsignedInt ;
}
public static int byteArrayToInt(byte[] bytes) {
int n = 0;
for (int i = 0; i < 4; i++) {
n += bytes[i] << i*8;
}
return n;
}
// 1.分配一个指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println(buf.position); //0
System.out.println(buf.limit); //1024
System.out.println(buf.capacity); //1024
System.out.println(buf.mark);
// 2.利用put()方法进行存储数据
String str = "hello nio";
buf.put(str.getBytes());
System.out.println(buf.position); //9
System.out.println(buf.limit); //1024
System.out.println(buf.capacity); //1024
System.out.println(buf.mark);
// 3.切换读取数据的模式
buf.flip();
System.out.println(buf.position); //0
System.out.println(buf.limit); //1024
System.out.println(buf.capacity); //1024
System.out.println(buf.mark);
// 4.利用get()方法读取数据
byte[] dst = new byte[buf.limit()];
buf.get(dst);
System.out.println(new String(dst, 0, dst.lenth));
System.out.println(buf.position); //9
System.out.println(buf.limit); //9
System.out.println(buf.capacity); //1024
System.out.println(buf.mark
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class Test {
/**
* String 转换 ByteBuffer
* @param str
* @return
*/
public static ByteBuffer getByteBuffer(String str) {
return ByteBuffer.wrap(str.getBytes());
}
/**
* ByteBuffer 转换 String
* @param buffer
* @return
*/
public static String getString(ByteBuffer buffer) {
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
try {
charset = Charset.forName("UTF-8");
decoder = charset.newDecoder();
// charBuffer = decoder.decode(buffer);//用这个的话,只能输出来一次结果,第二次显示为空
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
return charBuffer.toString();
}
catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
}
生活, 一半是回忆, 一半是继续。 把所有的不快给昨天, 把所有的希望给明天, 把所有的努力给今天。