# Converting Hex to Binary and storing bits in an array

0

I'm trying to write a function in C to convert a Hex value into its binary representation then store each bit separately in an array.

So currently I'm using this long winded method..

``````void HexToBinary(int *bits, unsigned int hex)
{
bits = (hex & 0x90000000) >> 31;
bits = (hex & 0x50000000) >> 30;
bits = (hex & 0x30000000) >> 29;
bits = (hex & 0x10000000) >> 28;
bits = (hex & 0x09000000) >> 27;
bits = (hex & 0x05000000) >> 26;
bits = (hex & 0x03000000) >> 25;
bits = (hex & 0x01000000) >> 24;
bits = (hex & 0x00900000) >> 23;
bits = (hex & 0x00500000) >> 22;
bits = (hex & 0x00300000) >> 21;
bits = (hex & 0x00100000) >> 20;
bits = (hex & 0x00090000) >> 19;
bits = (hex & 0x00050000) >> 18;
bits = (hex & 0x00030000) >> 17;
bits = (hex & 0x00010000) >> 16;
bits = (hex & 0x00009000) >> 15;
bits = (hex & 0x00005000) >> 14;
bits = (hex & 0x00003000) >> 13;
bits = (hex & 0x00001000) >> 12;
bits = (hex & 0x00000900) >> 11;
bits = (hex & 0x00000500) >> 10;
bits = (hex & 0x00000300) >> 9;
bits = (hex & 0x00000100) >> 8;
bits = (hex & 0x00000090) >> 7;
bits = (hex & 0x00000050) >> 6;
bits = (hex & 0x00000030) >> 5;
bits = (hex & 0x00000010) >> 4;
bits = (hex & 0x00000009) >> 3;
bits = (hex & 0x00000005) >> 2;
bits = (hex & 0x00000003) >> 1;
bits = (hex & 0x00000001);
}
``````

Which takes a 8 char (32-bit) hex value and using & and bit shifts identifies the wanted bit and then stores it in the array for each bit in the hex value.

Obviously this is a very long method and not very nice. I'm looking for a shorter and easier way to do it.

The bits have to be stored separately in the array and not in quads as I have to individually access each bit in the program.

Thanks

c
binary
hex

2
``````for (int i=0;i<32;i++) {
bits[i]=hex&1;
hex>>=1;
}
``````
0

Just use a loop:

``````void HexToBinary(int *bits, unsigned int hex) {
for (int i = 0; i < 32; ++i) {
bits[i] = (hex >> i) & 1;
}
}
``````

You don't have to put all bits to an array to individually access each bit. You can also access it with the function:

``````int bit(unsigned int hex, int i) {
return (hex >> i) & 1;
}
``````

or with the macro:

``````#define BIT(hex, i) ((hex >> i) & 1)
``````

User contributions licensed under CC BY-SA 3.0