Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Priniting negative byte value in Binary String.

Narasimha Rao B.
Ranch Hand
Posts: 205
Hi,
When i excute the below code, am getting the below output,
--------------------
111000
1111111111001000
111000
11111111111111111111111111001000
11111111111111111111111111001000
-----------------------------
Can any of you explain the reson behind printing the 32 bits for byte. I am expecting the output for the 4th line, -- 11001000.i.e., i am expecting only 8 bits( because that is the size of number of bits can hold by byte), but the output contains 32 bits.

public class A {
public static void main (String[] args) {
final int in = 56;
char ch=in;
byte by=in;
char ch1=(char)-in;
byte by1=(byte)-in;
System.out.println(Integer.toBinaryString(ch) );//1
System.out.println(Integer.toBinaryString(ch1) );//2
System.out.println(Integer.toBinaryString(by) );//3
System.out.println(Integer.toBinaryString(by1) );//4
System.out.println(Integer.toBinaryString(-in) );//5
}
}

Lawrence Chettiar
Ranch Hand
Posts: 62
Hi,
In simple terms you are getting the output of binary not of byte but of int why becoz
Integer.toBinaryString(-in)
if you check the api the method Integer.toBinaryString() takes a int parameter but since a byte can be expanded to int when you call this method with a byte value when the value reaches the method code its a int value and the representation of your negative byte value converted to int is as printed.
Now you might ask why is the positive value not of 32 bits the reason is the toBinaryString does not print leading zeros hence value 5 in byte / integer /long for that matter will be printed as
101 and not 0000 0101
Hope this helps you.

S Goyal
Greenhorn
Posts: 27
toBinaryString takes int as a parameter. So the byte gets promoted to int and so we get a 32 bit answer!

Narasimha Rao B.
Ranch Hand
Posts: 205
Hi Lawrence,
Thank you very much for your reply. I got what you are trying to say.
Based on your logic, in line no //2, negative char should be converted to int and output should be 32 bits rather than 16 bits, Why output is coming in 16 bits???
My second question is, What will happen when byte or short is converted to int?. Initially a byte will contain only 8 bits, when it is promoted to int, what are the values of other 24 bits, will they be zeros or ones, will they be adding on left side or right side of existing 8 bits.