简体   繁体   English

如何在Java中将字节重新解释为整数?

[英]How can I reinterpret a byte as an integer in java?

I have a problem with conversions of different types. 我对不同类型的转换有疑问。 In my code I am trying to use bytes and then convert them to an integer to be able to write x amount of bits from the integer to a storage of a kind. 在我的代码中,我尝试使用字节,然后将它们转换为整数,以便能够将x的位数从整数写入某种存储。

The problem is that when I have a negative number as byte and I convert it to an integer, the bit representation as an integer has all the leading bits set as 1. So when I try to save for example 10 bits from the integer, I get the leading bits as 1 instead of 0 as I expected. 问题是当我有一个负数作为字节并将其转换为整数时,作为整数的位表示形式会将所有前导位设置为1。因此,当我尝试从整数中保存例如10位时,我得到前导位为1而不是我期望的0。

Is there a way to reinterpret the byte as an integer while keeping the bit representation the same? 有没有办法在保持位表示相同的情况下将字节重新解释为整数? I do not need to care about the actual numerical value of the integer. 我不需要关心整数的实际数值。

From C++ I am used to having unsigned values which would prevent this issue, but now I am at loss with how to deal with this in java being limited to signed integers. 从C ++开始,我习惯于使用无符号值来防止出现此问题,但是现在我对如何在Java中将其处理仅限于有符号整数感到困惑。

Example: 例:

/*
    decimal: -28
    as byte: 11100100
    as integer: 11111111111111111111111111100100
    needed/expected integer: 00000000000000000000000011100100
*/
import java.util.*;
import java.lang.*;
import java.io.*;

class MyClass
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Integer.toBinaryString((byte)-28));
    }
}

https://ideone.com/VE960u https://ideone.com/VE960u

yourInt = yourByte & 255;

只需掩盖不需要的位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM