Reputation:
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
Upvotes: 0
Views: 1900
Reputation: 3743
A[0]= x & 255
A[1]= (x>> 8) & 255
A[2]= (x>>16) & 255
A[3]= (x>>24) & 255
...
Upvotes: 0
Reputation: 158
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.
Upvotes: 1
Reputation: 533462
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
Upvotes: 3