Convert from 2 or 4 bytes to signed/unsigned short/int

后端 未结 2 1513
粉色の甜心
粉色の甜心 2020-12-31 21:57

I have to convert bytes to signed/unsigned int or short.

The methods below are correct? Which is signed and which unsigned?

Byte order: LITTLE_ENDIAN

<
2条回答
  •  情深已故
    2020-12-31 22:38

    There is a problem with the 4-byte unsigned conversion, because it doesn't fit into an int. The routines below work correctly.

    public class IntegerConversion
    {
      public static int convertTwoBytesToInt1 (byte b1, byte b2)      // signed
      {
        return (b2 << 8) | (b1 & 0xFF);
      }
    
      public static int convertFourBytesToInt1 (byte b1, byte b2, byte b3, byte b4)
      {
        return (b4 << 24) | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
      }
    
      public static int convertTwoBytesToInt2 (byte b1, byte b2)      // unsigned
      {
        return (b2 & 0xFF) << 8 | (b1 & 0xFF);
      }
    
      public static long convertFourBytesToInt2 (byte b1, byte b2, byte b3, byte b4)
      {
        return (long) (b4 & 0xFF) << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
      }
    
      public static void main (String[] args)
      {
        byte b1 = (byte) 0xFF;
        byte b2 = (byte) 0xFF;
        byte b3 = (byte) 0xFF;
        byte b4 = (byte) 0xFF;
    
        System.out.printf ("%,14d%n", convertTwoBytesToInt1 (b1, b2));
        System.out.printf ("%,14d%n", convertTwoBytesToInt2 (b1, b2));
    
        System.out.printf ("%,14d%n", convertFourBytesToInt1 (b1, b2, b3, b4));
        System.out.printf ("%,14d%n", convertFourBytesToInt2 (b1, b2, b3, b4));
      }
    }
    

提交回复
热议问题