java short to byte_java基础之short转换byte[]

最近做个通信项目使用UDP Socket,所以数据的接发都与byte[]有关,

基本类型与byte[]转换作为基础知识,需要mark一下. 0x0与0x00的区别是前者4位,后者8位.

ByteArrayOutputStream buf = new ByteArrayOutputStream();

DataOutputStream out = new DataOutputStream(buf);

out.writeShort(301);

byte[] b1 = buf.toByteArray();

for(byte bb : b1) {

System.out.print(Integer.toHexString(bb & 0xFF) + " ");

}

byte[] buf2 = {0x01,0x2d};

ByteArrayInputStream bintput = new ByteArrayInputStream(buf2);

DataInputStream dintput = new DataInputStream(bintput);

short i = dintput.readShort();

System.out.print(i);

//io的各种关闭省略..

如果把301定义成int,那么转换后byte[]的长度是4,内容是0x00 0x00 0x01 0x2d,因为int型占4byte32位,而short是2byte16位,同时注意取值范围.

public static int byte2ToUnsignedShort(byte[] bytes, int off) {

int high = bytes[off];

int low = bytes[off + 1];

return (high << 8 & 0xFF00) | (low & 0xFF);

}

public static byte[] unsignedShortToByte2(int s) {

byte[] targets = new byte[2];

targets[0] = (byte) (s >> 8 & 0xFF);

targets[1] = (byte) (s & 0xFF);

return targets;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值