How do I print the binary representation of the first character in a string
i want to retrieve the binary values of the data in the file. so i have written the following the code:
while ((fileData = br.readLine()) != null) {
byte b[] = fileData.getBytes("UTF-8");
BigInteger bi = new BigInteger(b);
String s = bi.toString(2);
System.out.println("Original message in binary: " + s);
System.out.println("Original message len开发者_JAVA技巧gth: " + s.length());
}
output:
abca (this is the data in a text file)
Original message in binary: <here>1100001011000100110001101100001
Original message length: 31
Everything is fine but while i am printing the data in binary format i am not able to print the first bit (<here>
) can anyone help me?
For first character:
s.charAt(0);
EDIT: If you want to print the binary representation of first byte then try this:
String str = Integer.toBinaryString("abca".getBytes("UTF-8")[0]);
System.out.println(str);
EDIT 2: Try this for leading zeroes.
static String addLeadingZeroes(String s) {
int zeroes = s.length() % 8;
byte[] bzero = new byte[8 - zeroes];
Arrays.fill(bzero, (byte)0x30);
return new StringBuilder(new String(bzero)).append(s).toString();
}
and call as
System.out.println("Original message in binary: "+ addLeadingZeroes(s));
I assume what you're saying is that when the first binary digit is a "0", that it is not displayed. If you want to insure that you're displaying a full 32 binary digits, you can use the following code.
public static final THIRTYTWO_ZEROS = "00000000000000000000000000000000";
String s = bi.toString(2);
s = THIRTYTWO_ZEROS.substring(s.length) + s;
This has the effect of padding your string with preceding "0" characters to a length of 32 characters.
精彩评论