Can we make unsigned byte in Java

前端 未结 16 1264
青春惊慌失措
青春惊慌失措 2020-11-22 08:02

I am trying to convert a signed byte in unsigned. The problem is the data I am receiving is unsigned and Java does not support unsigned byte, so when it reads the data it tr

16条回答
  •  一整个雨季
    2020-11-22 08:39

    Complete guide for working with unsigned bytes in Java:

    Unsigned byte in Java

    (Source for this answer.)


    The Java Language does not provide anything like the unsigned keyword. A byte according to the language spec represents a value between −128 - 127. For instance, if a byte is cast to an int Java will interpret the first bit as the sign and use sign extension.

    That being said, nothing prevents you from viewing a byte simply as 8 bits and interpret those bits as a value between 0 and 255. Just keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte, then that method accepts a value between −128 and 127 unless explicitly stated otherwise.

    Here are a couple of useful conversions / manipulations for your convenience:

    Conversions to / from int

    // From int to unsigned byte
    int i = 200;                    // some value between 0 and 255
    byte b = (byte) i;              // 8 bits representing that value
    

    // From unsigned byte to int
    byte b = 123;                   // 8 bits representing a value between 0 and 255
    int i = b & 0xFF;               // an int representing the same value
    

    (Or, if you're on Java 8+, use Byte.toUnsignedInt.)

    Parsing / formatting

    Best way is to use the above conversions:

    // Parse an unsigned byte
    byte b = (byte) Integer.parseInt("200");
    

    // Print an unsigned byte
    System.out.println("Value of my unsigned byte: " + (b & 0xFF));
    

    Arithmetics

    The 2-complement representation "just works" for addition, subtraction and multiplication:

    // two unsigned bytes
    byte b1 = (byte) 200;
    byte b2 = (byte) 15;
    
    byte sum  = (byte) (b1 + b2);  // 215
    byte diff = (byte) (b1 - b2);  // 185
    byte prod = (byte) (b2 * b2);  // 225
    

    Division requires manual conversion of operands:

    byte ratio = (byte) ((b1 & 0xFF) / (b2 & 0xFF));
    

提交回复
热议问题