How to Convert Int to Unsigned Byte and Back

前端 未结 10 658
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题