Sal-laS
Sal-laS

Reputation: 11649

Convert ASCII characters to binary (7-bit)

I need to convert ASCII characters to (7-bit) binary. I have seen this, but it gives me the binary value in 8 bits, meanwhile i want it to be in 7 bits. For instance:

C should be 1000011

CC should be 10000111000011

% should be 0100101

So, I changed the code to:

String s = "%";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (int j = 0; j < 7; j++) {
    int val =  bytes[j];
    for (int i = 0; i < 8; i++) {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
    binary.append("");
}

System.out.println("'" + s + "' to binary: " + binary);

and it complains with:

java.lang.ArrayIndexOutOfBoundsException: 1

in the line:

int val =  bytes[j];

To highlight:

I used

 for(int j=0;j<7;j++)
    int val =  bytes[j];

instead of

for (byte b : bytes) int val = b;

Upvotes: 2

Views: 5128

Answers (3)

Dilip Singh Kasana
Dilip Singh Kasana

Reputation: 162

There are 2 changes in your code below :

        String s = "%";
        byte[] bytes = s.getBytes();
        StringBuilder binary = new StringBuilder();
        for (int j = 0; j < bytes.length; j++) {
            int val = bytes[j];
            for (int i = 0; i < 7; i++) {
                val <<= 1;
                binary.append((val & 128) == 0 ? 0 : 1);
            }
        }

        System.out.println("'" + s + "' to binary: " + binary);

Upvotes: 2

Greycon
Greycon

Reputation: 789

Here is some code which should give you a hint; it takes each character as a byte, then walks along each of the least significant 7 bits, using a bitmask. Just add your string builder code;

public static void main(String[] args) {
    String s = "A";
    byte[] bytes = s.getBytes();

    for (int bytePos = 0; bytePos < bytes.length; ++bytePos) {
        byte b = bytes[bytePos];
        byte mask = 0b1000000;
        while (mask > 0) {
            System.out.println(b & mask);
            mask /= 2;
        }
    }
}

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120644

Change your first for loop from:

for (int j = 0; j < 7; j++) {

To:

for (int j = 0; j < bytes.length; j++) {

You want this outer loop to loop over all of the elements of bytes.

Upvotes: 3

Related Questions