java 三个字节,我怎样才能把一个int到Java的三个字节?

I am trying to convert an int into three bytes representing that int (big endian).

I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.

For example:

int myInt;

// some code

byte b1, b2 , b3; // b1 is most significant, then b2 then b3.

*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.

解决方案

To get the least significant byte:

b3 = myInt & 0xFF;

The 2nd least significant byte:

b2 = (myInt >> 8) & 0xFF;

And the 3rd least significant byte:

b1 = (myInt >> 16) & 0xFF;

Explanation:

Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值