How to Convert Int to Unsigned Byte and Back

前端 未结 10 650
死守一世寂寞
死守一世寂寞 2020-11-28 23:04

I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.

I also need to convert that byte ba

相关标签:
10条回答
  • 2020-11-28 23:25

    If you just need to convert an expected 8-bit value from a signed int to an unsigned value, you can use simple bit shifting:

    int signed = -119;  // 11111111 11111111 11111111 10001001
    
    /**
     * Use unsigned right shift operator to drop unset bits in positions 8-31
     */
    int psuedoUnsigned = (signed << 24) >>> 24;  // 00000000 00000000 00000000 10001001 -> 137 base 10
    
    /** 
     * Convert back to signed by using the sign-extension properties of the right shift operator
     */
    int backToSigned = (psuedoUnsigned << 24) >> 24; // back to original bit pattern
    

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

    If using something other than int as the base type, you'll obviously need to adjust the shift amount: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    Also, bear in mind that you can't use byte type, doing so will result in a signed value as mentioned by other answerers. The smallest primitive type you could use to represent an 8-bit unsigned value would be a short.

    0 讨论(0)
  • 2020-11-28 23:29

    The solution works fine (thanks!), but if you want to avoid casting and leave the low level work to the JDK, you can use a DataOutputStream to write your int's and a DataInputStream to read them back in. They are automatically treated as unsigned bytes then:

    For converting int's to binary bytes;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    int val = 250;
    dos.write(byteVal);
    ...
    dos.flush();
    

    Reading them back in:

    // important to use a (non-Unicode!) encoding like US_ASCII or ISO-8859-1,
    // i.e., one that uses one byte per character
    ByteArrayInputStream bis = new ByteArrayInputStream(
       bos.toString("ISO-8859-1").getBytes("ISO-8859-1"));
    DataInputStream dis = new DataInputStream(bis);
    int byteVal = dis.readUnsignedByte();
    

    Esp. useful for handling binary data formats (e.g. flat message formats, etc.)

    0 讨论(0)
  • 2020-11-28 23:41

    Handling bytes and unsigned integers with BigInteger:

    byte[] b = ...                    // your integer in big-endian
    BigInteger ui = new BigInteger(b) // let BigInteger do the work
    int i = ui.intValue()             // unsigned value assigned to i
    
    0 讨论(0)
  • 2020-11-28 23:42

    Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

    In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

    To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

    0 讨论(0)
  • 2020-11-28 23:45

    If you want to use the primitive wrapper classes, this will work, but all java types are signed by default.

    public static void main(String[] args) {
        Integer i=5;
        Byte b = Byte.valueOf(i+""); //converts i to String and calls Byte.valueOf()
        System.out.println(b);
        System.out.println(Integer.valueOf(b));
    }
    
    0 讨论(0)
  • 2020-11-28 23:47

    in java 7

    public class Main {
        public static void main(String[] args) {
            byte b =  -2;
            int i = 0 ;
            i = ( b & 0b1111_1111 ) ;
            System.err.println(i);
        }
    }
    

    result : 254

    0 讨论(0)
提交回复
热议问题