网站运营解决方案,下载京东购物商城app,购买网站源码注意事项,淄博网站建设详细策划文章目录 前言一、无符号字节转为int1.前置知识2.无符号转int代码3.Java中字节转为int 二、字节缓冲流1.基础知识2.String与ByteBuffer转换 总结 前言
Java 中基本类型都是有符号数值#xff0c;如果接收到了 C/C 处理的无符号数值字节流#xff0c;将出现转码错误。 提示如果接收到了 C/C 处理的无符号数值字节流将出现转码错误。 提示以下是本篇文章正文内容下面案例可供参考
一、无符号字节转为int
1.前置知识
在线进制转换https://tool.oschina.net/hexconvert 之前在解析 webscoket 传输得二进制数据时因为二进制数据传输的是 uint32 无符号整数需要把有符号的字节转为正常的 uint32 代表无符号整数只能存正整数在内存中占4个字节byte[4]0到4294967295Java中 int 为32位有符号整数占4字节-2147483648 到 2147483648。
2.无符号转int代码
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[index3]));sceondByte (0x000000FF ((int) buf[index2]));thirdByte (0x000000FF ((int) buf[index1]));fourthByte (0x000000FF ((int) buf[index]));anUnsignedInt ((long) (firstByte 24 | sceondByte 16 | thirdByte 8 | fourthByte)) 0xFFFFFFFFL;return anUnsignedInt ;
}3.Java中字节转为int
public static int byteArrayToInt(byte[] bytes) {int n 0;for (int i 0; i 4; i) {n bytes[i] i*8;}return n;
}二、字节缓冲流
1.基础知识
分配一个指定大小的缓冲区
// 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); 利用put()方法进行存储数据
// 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);利用get()方法读取数据
// 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.mark2.String与ByteBuffer转换
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 ; } }
}总结
生活 一半是回忆 一半是继续。 把所有的不快给昨天 把所有的希望给明天 把所有的努力给今天。