How to Convert Int to Unsigned Byte and Back

前端 未结 10 654
死守一世寂寞
死守一世寂寞 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:50

    Even though it's too late, I'd like to give my input on this as it might clarify why the solution given by JB Nizet works. I stumbled upon this little problem working on a byte parser and to string conversion myself. When you copy from a bigger size integral type to a smaller size integral type as this java doc says this happens:

    https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3 A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

    You can be sure that a byte is an integral type as this java doc says https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html byte: The byte data type is an 8-bit signed two's complement integer.

    So in the case of casting an integer(32 bits) to a byte(8 bits), you just copy the last (least significant 8 bits) of that integer to the given byte variable.

    int a = 128;
    byte b = (byte)a; // Last 8 bits gets copied
    System.out.println(b);  // -128
    

    Second part of the story involves how Java unary and binary operators promote operands. https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2 Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    If either operand is of type double, the other is converted to double.

    Otherwise, if either operand is of type float, the other is converted to float.

    Otherwise, if either operand is of type long, the other is converted to long.

    Otherwise, both operands are converted to type int.

    Rest assured, if you are working with integral type int and/or lower it'll be promoted to an int.

    // byte b(0x80) gets promoted to int (0xFF80) by the & operator and then
    // 0xFF80 & 0xFF (0xFF translates to 0x00FF) bitwise operation yields 
    // 0x0080
    a = b & 0xFF;
    System.out.println(a); // 128
    

    I scratched my head around this too :). There is a good answer for this here by rgettman. Bitwise operators in java only for integer and long?

提交回复
热议问题