如何在Java中使用bitshifting [英] How to use bitshifting in Java
问题描述
我正在尝试构建一个IP头。
I am trying to construct an IP header.
IP标头包含以下字段:版本,IHL,DSCP等。我想填充一个字节数组,以便我可以以字节为单位存储信息。
An IP header has the following fields: Version, IHL, DSCP etc. I would like to populate a Byte Array such that I can store the information in bytes.
然而,我感到困惑的是版本字段只有4位宽。国际人道法也只有4位宽。如何将这两个字段的值拟合为一个字节?我需要做位移吗?
Where I get confused however is that the Version field is only 4 bits wide. IHL is also only 4 bits wide. How do I fit the values of both of those fields to be represented as a byte? Do I need to do bitshifting?
例如。版本= 4,IHL = 5.我需要创建一个等于0100 0101 = 45h或69十进制的字节。
E.g. Version = 4, IHL = 5. I would need to create a byte that would equal 0100 0101 = 45h or 69 decimal.
推荐答案
(byte) (4 << 4) | 5
这将值4移到左边,然后将低4位设置为值5. / p>
This shifts the value 4 to the left, then sets lower 4 bits to the value 5.
-
00000100
一个值(4
) -
01000000
向左移4位后(<<< 4
) -
00000101
另一个值(5
) -
01000101
#2和#3的按位OR(|
)的结果/ li>
00000100
A value (4
)01000000
After shifting left 4 bits (<< 4
)00000101
Another value (5
)01000101
The result of a bitwise OR (|
) of #2 and #3
因为操作数是 int
类型(即使它们是<$ c) $ c> byte 值,当 |
等运算符时,它们会被提升为 int
对他们采取行动),最终结果需要一个演员表存储在字节
。
Because the operands are int
types (and even if they were byte
values, they'd be promoted to int
when operators like |
act on them), the final result needs a cast to be stored in a byte
.
如果您正在使用 byte
值作为任何按位运算中的操作数,隐式转换为 int
会导致意外结果。如果要将字节
视为在该转换中未签名,请使用按位AND(&
) :
If you are using byte
values as operands in any bitwise operations, the implicit conversion to int
can cause unexpected results. If you want to treat a byte
as if it were unsigned in that conversion, use a bitwise AND (&
):
byte b = -128; // The byte value 0x80, -128d
int uint8 = b & 0xFF; // The int value 0x00000080, 128d
int i = b; // The int value 0xFFFFFF80, -128d
int uintr = (b & 0xFF) | 0x04; // 0x00000084
int sintr = b | 0x04; // 0xFFFFFF84
这篇关于如何在Java中使用bitshifting的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!