1

For an assignment I am trying to convert a string into a 7-bit binary. However, we are not allowed to use Integer.toBinaryString(int). This is what I have so far

public static int[] encodeToBit(String str) {   

    int[] convertString = new int[str.length() * 7];

    for (int i = 0; i < convertString.length; i++) {
        convertString[i] = (int)str.charAt(i);

        for (int j = convertString.length; j >=0 ; j--) {

            while (true) {
            convertString[i] =

            }
        } 
    }
    return convertString;
}

Any advice for how to convert an integer ASCII representation of a char into a 7-bit binary.

Edit: For example, encodeToBit(“C") should output the array

[ 1, 0, 0, 0, 0, 1, 1 ]

Yaz
  • 23
  • 2
  • 6

2 Answers2

0

I assume you want an array of 0 and 1s with 7 per character..

public static byte[] encodeTo7Bits(String str) {
    byte[] bytes = new byte[str.length() * 7];
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        assert ch < 128;
        for (int j = 0; j < 7; j++) 
            bytes[i * 7 + j] = (byte) ((ch >> (7 - j)) & 1);
    }
    return bytes;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Yes, I need an array of 1s and 0s made up of 7 characters. However, I need to return an int []. So would I just set my convertString array equal to a byte array? – Yaz Apr 09 '16 at 17:20
  • @Yaz not sure why you would nee an `int` to store a 0 or 1, but you can easily change my answer to use a `int[]` instead. – Peter Lawrey Apr 09 '16 at 17:21
0

This code also works

private static int[] getBinaryInt(String s) {
    byte[] bytes = s.getBytes();
    int[] binary = new int[7];
    for (byte b : bytes) {
        int val = b;
        for (int i = 0; i < 7; i++) {
            binary[i] = ((val & 64) == 0 ? 0 : 1);
            val <<= 1;
        }
    }
    return binary;
}
Gowsikan
  • 5,571
  • 8
  • 33
  • 43