Edward Banfa
Edward Banfa

Reputation: 17

Java integer to byte array to short

I am trying to convert an Integer to a byte array (array of 4 bytes) and then I will extract the last 4 bits of each byte, then I will create a short from those last 4 digits of each bytes.

I have the following code but it always prints zero.


    private static short extractShort(byte[] byteArray) {
        short s = 1;
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        for(int i = 0; i < byteArray.length; i++) {
            byte lastFourBytes = extractLast4Bits(byteArray[i]);
            // Uses a bit mask to extract the bits we are interested in
            byteBuffer.put(lastFourBytes);
        }
       return  ByteBuffer.wrap(byteBuffer.array()).getShort();
    }


    private static byte extractLast4Bits(byte byteParam) {
        return  (byte) ( byteParam & 0b00001111);
    }

    private static byte[] intToByteArray(int i) {
        return new byte[] {
            (byte)((i >> 24) & 0xff),
            (byte)((i >> 16) & 0xff),
            (byte)((i >> 8) & 0xff),
            (byte)((i >> 0) & 0xff),
         };
    }

}

Any help will be sincerely appreciated

Upvotes: 1

Views: 271

Answers (1)

WJS
WJS

Reputation: 40024

Once you get the byte array, try this..


    short val = 0;
    for (byte b : bytes) {
       val <<= 4;
       val |= (b&0xf)
    }

If you want to do it starting from an int, you can do it like this.

      int v = 0b1110_1010_1111_1001_1010_1000_1010_0111;
      short verify = (short) 0b1010_1001_1000_0111;
      // initialize a short value
      short val = 0;

      // increment from 24 to 0 by 8's  the loop will
      // repeat 4 times.
      for (int i = 24; i >= 0; i -= 8) {
         // start by shifting the result left 4 bits
         // first time thru this does nothing.
         val <<= 4;

         // Shift the integer right by i bits (first time is
         // 24, next time is 16, etc
         // then mask off the lower order 4 bits of the right
         // most byte and OR it to the result(val).
         // then when the loop continues, val will be
         // shifted left 4 bits to allow for the next "nibble"

         val |= ((v >> i) & 0xf);
      }
      System.out.println(val);
      System.out.println(verify);

For more information on bitwise operators, check out this Wikipedia link.

Upvotes: 1

Related Questions