When you write binary[i] = 0000
you are saying that you are assigning octal constant to binary[i]
which is 0
. All leading zeros are omitted. But the first zero indicates that the constant should be interpretend as octal one.
Another example: int x = 000011
just means that x
is assigned an octal value of 11
or decimal value of 9
. That is how compiler understands constants.
When the value is stored in the memory it knows nothing about what base it was written from. All numbers are stored in binary representation as you know. However numbers may have many views in different bases. We are convenient to work with numbers in decimal view.
There are many specifiers for printf
for integer to output some its representations, they are %u
- decimal, %x
- hex, %o
- for octal. Unfortunately no option to output binary number representation. In order to output number in base2 one should manually calculate each binary digit (0 or 1) and print them in corresponding order.
Try using the following code to output binary number representation.
void printInBase2(int n) {
if(n == 0) { printf("0"); return; }
int b = 0;
for(b = 0; n >> b + 1; b++);
for(; b >= 0; b--)
printf("%c", (n >> b) % 2 + '0');
}
To read a number from a hexadecimal representation which is stored in string you can do this:
unsigned int number;
char hexstring[] = "24020004";
sscanf(hexstring, "%x", &number);
In case you want to store binary digits in int binary[]
array you can do similar thing you did with string
case '0': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 0, binary[4 * i] = 0; break;
case '1': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 0, binary[4 * i] = 1; break;
case '2': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 1, binary[4 * i] = 0; break;
...
case 'f': binary[4 * i + 3] = 1, binary[4 * i + 2] = 1, binary[4 * i + 1] = 1, binary[4 * i] = 1; break;
This way you will store each binary digit separately. Note that you binary
array should be 4 times longer than hexstring
.