1

I have a char holding different characters, and I would like to print the binary value of these into two 4 bytes sections. I am adding a 1 at the beginning so that they would be 4 each.

    System.out.println(1 + Integer.toString(mychar[i],2));

I am using a for loop to go through the different characters and create a table. By doing this I can get the binary value plus the one. But i don't know how to separate it into two 4 bytes.

Lets assume that mychar[i] holds the String bryan. The output should be the following.

 b    1110 0010
 r    1111 0010
 y    1111 1001
 a    1110 0001
 n    1110 1110 
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • 1
    Can you provide an example value of `mychar` and what output you'd want to get for it? – Mureinik Nov 07 '15 at 19:40
  • 1
    @Mureinik,@SkinnyJ, I just edited it, it didn't came out as a table but that is mainly what I want. – El rascabuches Nov 07 '15 at 19:53
  • 3
    Why are you adding `1`? The actual value for ASCII "b" should be `01100010`. – RealSkeptic Nov 07 '15 at 19:53
  • 1
    @RealSkeptic, I am confused I thought that the ASCII value for "b" was 98. i was adding the 1 to create a two sections of 4 bytes. Thanks for making that table for me by the way. – El rascabuches Nov 07 '15 at 19:57
  • 1
    Yes, 98 in decimal is 64 + 32 + 2, which means `01100010`. Your output, however, adds a `1` on the left, and this indicates adding another 128. – RealSkeptic Nov 07 '15 at 20:00
  • 1
    That about using [this question](http://stackoverflow.com/q/4421400/589259) for 8 characters, then split the string in two and add a space in the middle? – Maarten Bodewes Nov 07 '15 at 20:00
  • 1
    @RealSkeptic, Understood, then I guess I can just use the ASCII value and splt it in two, but I don't know how to do the splitting process. Any ideas? – El rascabuches Nov 07 '15 at 20:03
  • 1
    These are 4 bit sections, called "nibbles", they are not bytes. They can be represented by 4 binary digits, which are characters. Characters are not bytes either. – Maarten Bodewes Nov 07 '15 at 20:08

4 Answers4

3

I've used this answer to come to a solution:

private static String toBinaryRepresentation(String name) {
    // 11 is size of "0000 0000\r\n
    StringBuilder sb = new StringBuilder(name.length() * 11);
    for (int i = 0; i < name.length(); i++) {
        String binRep = toBinaryRepresentation(name.charAt(i));
        sb.append(String.format("%s%n", binRep));
    }
    return sb.toString();
}

private static String toBinaryRepresentation(char c) {
    if (c > 0xFF) {
        throw new IllegalArgumentException("Character value too high to print");
    }
    int highNibble = (c >> 4) & 0xF;
    String highBinaryDigits = String.format("%4s", Integer.toBinaryString(highNibble)).replace(' ', '0');
    int lowNibble = c & 0xF;
    String lowBinaryDigits = String.format("%4s", Integer.toBinaryString(lowNibble)).replace(' ', '0');
    return String.format("%s %s", highBinaryDigits, lowBinaryDigits);
}

Which you can use by calling the function like this:

String name = "brian";
System.out.print(toBinaryRepresentation(name));

This prints:

0110 0010
0111 0010
0110 1001
0110 0001
0110 1110

So this first separates the high and low nibble and then prints the value using precisely 4 bits, even if they are zero.

Community
  • 1
  • 1
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
3

My personal favorite for zero-padding a small number (that is, a byte, a short etc) when converted to binary is:

String binaryRep = Integer.toBinaryString( 0x100 | mychar[i] & 0xff ).substring(1);
  • The & makes sure that no more than 8 bits are taken from mychar[i]
  • The 0x100 | part sets the 9th bit. This means all the zeros in the rightmost 8 bits will be represented in the result, which will be exactly 9 characters long.
  • Then taking the substring from 1 makes sure we take just the 8.

Of course, the above assumes a character that fits into 8 bits. If you try a Chinese or Arabic character it will basically just give you its rightmost 8 bits.

Whatever method you use for producing 8 zero-padded bits, you'll need to add the space in the middle. For my method above, we can make this modification:

public static String eightBitCharToBinary( char c ) {

    String charAsNineBits = Integer.toBinaryString( 0x100 | c & 0xff );
    return charAsNineBits.substring(1,5) + " " + charAsNineBits.substring(5,9);

}

Which does the same as above, but instead of just taking one substring, takes two substrings and puts a space in the middle.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
1
 public static void main(String []args){

  String [] mychar = {"bryan"};
   int len = mychar.length;

  // iterate over each mychar element
  for(int i =0; i< len ; i++){

 // get the first string from array
      String s = mychar[i];
      int length = s.length();

     //iterate over the string 
        for(int j =0; j< length ; j++){
            char ch = s.charAt(j);
       String str = Integer.toBinaryString(ch);
       // print each char
       System.out.print(ch+"  :  ");
   System.out.println(str.substring(0,4)+"  "+str.substring(3) );
        }
  }


 }
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
  • 1
    (a) I think that `mychar` is an array of `char`, though OP was a little confusing in this regard. (b) The real issue is the fact that `toBinaryString()` doesn't always return a string of length 8. Try it for the char `'#'`. – RealSkeptic Nov 07 '15 at 20:07
  • 1
    I see, so it is limited to numbers and letters probably. – El rascabuches Nov 07 '15 at 20:18
1
char c = 'b';
        String binaryString =Integer.toBinaryString(c);
        System.out.println("1" + binaryString.substring(0, 3) + "  " + binaryString.substring(3));
Sheebu PJ
  • 31
  • 3
  • 1
    Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves. – Jeen Broekstra Nov 08 '15 at 02:17
  • 1
    char c = 'b';Integer.toBinaryString(c) – Sheebu PJ Nov 08 '15 at 13:17
  • 1
    Integer.toBinaryString(c); gives string representation of bynarycode which is 7 digit number in this case. In println we prefix with "1' then concatenate first three digit . Then space and remaining 4 digit – Sheebu PJ Nov 08 '15 at 13:24