简体   繁体   中英

Convert 32bit binary string to byte

I am using FileInputStream to read a single byte at a time, I then turn it into a string using the Integer.toBinaryString(), and later need to cast it back into a byte.

here's my problem: java uses a 32bit byte, meaning that my string returned by Integer.toBinaryString() has a length of 32, and I've been getting quite frustrated trying to convert that back into a byte because methods like Byte.valueOf() and so on, all throw an error pertaining to the value being out of byte range.

Am I missing something? Or do I need to develop my own method.

I found the simple answer :|

public class abc
{
    public static void main (String[] args)
    {
        byte b = -1;
        String binString = Integer.toBinaryString(b); //value 1111,1111,1111,1111,1111,1111,1111,1111
        new BigInteger(binString, 2).byteValue(); //value -1 
    }
}

It truncates the binString, but that doesn't effect the byte value, because the 24 bits on the left aren't really relevant to the byte.

Now, in the example above I'm using a BigInteger and its byteValue() method, the reason for that, and why I'm not just using a 0xff solution, is because the Integer.toBinaryString() in the code above will return a string digit (32 1's) with a length of 32 and this cannot be casted into an int or even a long, because it is too large a number/value. As a result of that, not being able to cast it into an int or long, one can't perform operations like & on it, so the solution is to trim the string of the of the 24 bits on the left, then one can cast/convert the shorter string into an int, which is what BigInteger does in the code above.

The byte will still maintain its value, because the value is only contained in the 8 bits on the right(staying true to what a byte is). The added 24 bits that java sometimes adds to the 8 bit byte, is for java's own purposes and can be ignored if need be, such as the example, the problem which spawned this thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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