0

i have used the following statement byte[3]=(byte)0x80 0x80 is an hex value of 128 and i have also tried this statement byte[3]=(byte) 128

in the first case, while printing i am getting the output as -128 in the second case, output is -1

Now how can i solve this. Is there any other way to store 10000000 into a byte array

3 Answers 3

3

The problem is not how you put the value in, its how you get it out.

byte[] bytes = new byte[4];
bytes[3] = (byte) 128;
int num = bytes[3] & 0xFF; 
System.out.println(num);

prints

128
Sign up to request clarification or add additional context in comments.

Comments

1

The computer stores the value in binary anyway, seems like your problem is outputting it in binary form.

Integer.toBinaryString(byte[3]);

should do the trick.

Edit: misread your question, but as others have said you will need to make sure the variable is unsigned to store a positive value over 127.

Comments

0
A[0]=      x  & 255
A[1]= (x>> 8) & 255
A[2]= (x>>16) & 255
A[3]= (x>>24) & 255
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.