0

I have long value, which i want to convert ot byte array. I use this function

      public static byte[] longToByteArray(long value) {
        byte[] result = new byte[8];
        for(int i = 0; i < 8; i++) {
          result[i] = (byte)(value & 0xFF);
          System.out.println(result[i]);
          System.out.println(Integer.toBinaryString(result[i]));
          value >>>= 8;
        } 
        return result;
      }

and output data looks like

18
10010
-12
11111111111111111111111111110100
88
1011000
83
1010011
0
0
0
0
0
0
0
0

Why i have too much 1 in binary view of -12, and how can i get it like

11110100
m_neo
  • 1
  • 4

4 Answers4

0

Your -12 is coming out as 11111111111111111111111111110100 because it is a negative number encoded in 2's complement format using all 32-bits available to it as it is being parsed as an integer.

If you only want the final 8 bits, you'll probably have to format it like that. Check this answer: How to convert a byte to its binary string representation

Community
  • 1
  • 1
Evan Knowles
  • 7,426
  • 2
  • 37
  • 71
0

That's because Integer.toBinaryString(result[i]) converts your byte to int (32 bits), and also, bytes are represented from -128 to 127, so values grater than 127 are being represented as negative numbers; hence, your byte ends up being a negative int. to solve it you can change this line:

System.out.println(Integer.toBinaryString(result[i]));

for this one:

System.out.println(Integer.toBinaryString(result[i] & 0xFF));
morgano
  • 17,210
  • 10
  • 45
  • 56
  • -12 is a negative integer. Also, I think you meant `System.out.println(Integer.toBinaryString(result[i] & 0xFF));` (single `&`) – Evan Knowles Apr 24 '14 at 05:38
  • @EvanKnowles sure it is, is there anything you want to clarify? – morgano Apr 24 '14 at 05:39
  • @EvanKnowles you're right, it is '&', not '&&', I'm going to delete my answer, can you please add the lines to your answer? the OP also asked for a solution – morgano Apr 24 '14 at 05:43
0

The reason is that even though you do (byte)(value & 0xFF) when you call Integer.toBinaryString it is being converted back to a 32 bit integer and you are getting proper output for -12 integer.

One simple solution is to convert negative byte values (-128 to -1) to be positive unsigned byte values (128 to 255). This is done simply by testing for negative and adding 256, like such:

int b = (int)(value & 0xFF);
if (b<0) {
    b = b + 256;
}

This is done in an integer data type, but the resulting value is 0..255 which is appropriate for an unsigned byte. So now, it turns out, instead of -12 you will have 244 but it turns out that the binary representation of 244 is the same as an 8-bit version of -12. Try it out!

AgilePro
  • 5,588
  • 4
  • 33
  • 56
0

you can use JBBP

byte [] packed = JBBPOut.BeginBin().Long(aLongValue).End().toByteArray();
Igor Maznitsa
  • 833
  • 7
  • 12