How to addition on bit with loop?

-1

For example, I have a number 104 and I want to change to a bit then add one bit every time.

String str = "h";
            String binary = new BigInteger(str.getBytes()).toString(2);
            int decimal = 0;
            int y =  Integer.valueOf(binary);
            System.out.println(y);
            System.out.println(y);
            y = y + 0x00000001;
          
            String z = String.valueOf(y);
            System.out.println("V  " + z);
            //byte[] bytes1 = z.getBytes("US-ASCII");
            decimal = Integer.parseInt(z, 2);
            System.out.println(decimal);

I get an error that "xception in thread "main" java.lang.NumberFormatException: For input string: "2" under radix 2"

java
asked on Stack Overflow Jan 2, 2021 by Java noob

1 Answer

0

Not sure what you mean by "add one bit".

Did you mean to add 1 to the binary number, i.e. simply increment the number like this?

char ch = 'h';
int num = ch;
print(num);
for (int i = 0; i < 10; i++) {
    num++;
    print(num);
}
static void print(int num) {
    System.out.println("Decimal: " + Integer.toString(num) +
                       "  Hex: " + Integer.toHexString(num) +
                       "  Binary: " + Integer.toBinaryString(num));
}

Output

Decimal: 104  Hex: 68  Binary: 1101000
Decimal: 105  Hex: 69  Binary: 1101001
Decimal: 106  Hex: 6a  Binary: 1101010
Decimal: 107  Hex: 6b  Binary: 1101011
Decimal: 108  Hex: 6c  Binary: 1101100
Decimal: 109  Hex: 6d  Binary: 1101101
Decimal: 110  Hex: 6e  Binary: 1101110
Decimal: 111  Hex: 6f  Binary: 1101111
Decimal: 112  Hex: 70  Binary: 1110000
Decimal: 113  Hex: 71  Binary: 1110001
Decimal: 114  Hex: 72  Binary: 1110010

Or did you perhaps mean to add a 1-bit at the end, like this?

char ch = 'h';
int num = ch;
print(num);
for (int i = 0; i < 10; i++) {
    num = (num << 1) | 1;
    print(num);
}

Output

Decimal: 104  Hex: 68  Binary: 1101000
Decimal: 209  Hex: d1  Binary: 11010001
Decimal: 419  Hex: 1a3  Binary: 110100011
Decimal: 839  Hex: 347  Binary: 1101000111
Decimal: 1679  Hex: 68f  Binary: 11010001111
Decimal: 3359  Hex: d1f  Binary: 110100011111
Decimal: 6719  Hex: 1a3f  Binary: 1101000111111
Decimal: 13439  Hex: 347f  Binary: 11010001111111
Decimal: 26879  Hex: 68ff  Binary: 110100011111111
Decimal: 53759  Hex: d1ff  Binary: 1101000111111111
Decimal: 107519  Hex: 1a3ff  Binary: 11010001111111111
answered on Stack Overflow Jan 2, 2021 by Andreas

User contributions licensed under CC BY-SA 3.0