如何在Java中屏蔽字节值?
我的问题是这样的。
我在Java中进行了一些字节计算。在某些计算中,我得到字节值的所需结果“2a”,但在某些计算中,我得到字节值的“ffffff9a”。我只想要结果“ffffff9a”中的“9a”值。我尝试过这个但没有成功。
byte a = (byte) b & 0xff;
其中 b 的值为“ffffff9a”字节值。
但是,当显示相同的过程时,就像
System.out.println(Integer.toHexString(b & 0xff));
我哪里出错了?我该怎么做才能获得我想要的价值?
谢谢
实际上我正在尝试将 8 位字符转换为 gsm 7 位。另外,如果那里有人可以帮助我解决这个问题,那也会很有帮助。字符串存储为字节数组,我必须将此字符串或 8 位字节转换为 7 位。
My problem is some like this.
I have some calculation in byte in Java. In some calculation I get my desired result "2a" in byte value but in some calculation I get "ffffff9a" in byte value. I just want the "9a" value in from the result "ffffff9a". I tried this but didn't work.
byte a = (byte) b & 0xff;
where b have value "ffffff9a" byte value.
But while displaying the same process works like
System.out.println(Integer.toHexString(b & 0xff));
Where am I going wrong? What can I do to get my desired value?
Thanks
Actually I am trying to convert 8 bit character into gsm 7 bit. Also if someone there can help me through this, it would be helpful too. String is stored as a byte array and I have to convert this string or 8 bit bytes into 7 bit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 中的
byte
类型是有符号的。它的范围是 [-128, 127]。即使
a
(其类型为byte
)将显示“正确的值”,将包含负值((byte) 0x92)。也就是说,
(int)a == 0x92
将为 false,因为转换为int
保留 值(负数和全部),而>(a & 0xff) == 0x92
将为 true。这是因为按位&
将表达式提升为int
类型,同时“屏蔽”“符号位”(不是真正的符号位,而是两个的假象)补充)。请参阅:Java 如何“转换”字节
快乐编码。
The
byte
type in Java is signed. It has a range of [-128, 127].Would show "the correct value" even though
a
, which is of typebyte
, will contain a negative value ((byte)0x92
). That is,(int)a == 0x92
will be false because the cast toint
keeps the value, negative and all, while(a & 0xff) == 0x92
will be true. This is because the bit-wise&
promotes the expression to anint
type while "masking away" the "sign bit" (not really sign bit, but artefact of two's complement).See: Java How To "Covert" Bytes
Happy coding.
您的初始代码是:
byte a = (byte) b & 0xff;
(byte)
类型转换仅适用于b
,它已经是一个byte
。然后,&
运算符将其扩展为int
,这样您就可以从int
得到结果“ffffff9a”。您需要确保类型转换适用于
&
的结果,而不仅仅是其第一个操作数:byte a = (byte)(b & 0xff);
请注意额外的一对括号。
Your initial code was:
byte a = (byte) b & 0xff;
The
(byte)
typecast only applied to theb
, which is already abyte
. The&
operator then widened that to anint
so you got the result "ffffff9a" from theint
.You need to ensure that you typecast applies to the result of the
&
, not just to its first operand:byte a = (byte)(b & 0xff);
Note the extra pair of parentheses.