如何将整数拆分为2字节二进制? [英] How do I split an integer into 2 byte binary?

查看:487
本文介绍了如何将整数拆分为2字节二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

private int width = 400;
private byte [] data = new byte [2];  

我想将整数width拆分为两个字节,并将数据[0]加载到高位具有低字节的字节和数据[1]。

I want to split the integer "width" into two bytes and load data[0] with the high byte and data[1] with the low byte.

这是二进制值400 = 1 1001 0000
所以data [0]应该包含0000 0001
和data [1]应包含1001 0000

That is binary value of 400 = 1 1001 0000 so data[0] should contain 0000 0001 and data[1] should contain 1001 0000

推荐答案

使用简单的按位运算:

data[0] = (byte) (width & 0xFF);
data[1] = (byte) ((width >> 8) & 0xFF);

工作原理:


  • & 0xFF 屏蔽除最低8位之外的所有字符。

  • >> 8 通过将所有位向右移动8位来丢弃最低8位。

  • 转换为字节是必要的,因为这些按位操作适用于 int 并返回 int ,这是一个比 byte 更大的数据类型。这种情况是安全的,因为所有非零位都适合字节。有关详细信息,请参阅 转化和促销

  • & 0xFF masks all but the lowest eight bits.
  • >> 8 discards the lowest 8 bits by moving all bits 8 places to the right.
  • The cast to byte is necessary because these bitwise operations work on an int and return an int, which is a bigger data type than byte. The case is safe, since all non-zero bits will fit in the byte. For more information, see Conversions and Promotions.

编辑: Taylor L 正确评论虽然>> 在这种情况下有效但如果你概括了这个,它可能会产生不正确的结果代码到四个字节(因为在Java中, int 是32位)。在这种情况下,最好使用>>> 而不是>> 。有关详细信息,请参阅关于 Bitwise和Bit的Java教程转移运算符

Taylor L correctly remarks that though >> works in this case, it may yield incorrect results if you generalize this code to four bytes (since in Java an int is 32 bits). In that case, it's better to use >>> instead of >>. For more information, see the Java tutorial on Bitwise and Bit Shift Operators.

这篇关于如何将整数拆分为2字节二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆