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[31] = (hex & 0x90000000) >> 31;
bits[30] = (hex & 0x50000000) >> 30;
bits[29] = (hex & 0x30000000) >> 29;
bits[28] = (hex & 0x10000000) >> 28;
bits[27] = (hex & 0x09000000) >> 27;
bits[26] = (hex & 0x05000000) >> 26;
bits[25] = (hex & 0x03000000) >> 25;
bits[24] = (hex & 0x01000000) >> 24;
bits[23] = (hex & 0x00900000) >> 23;
bits[22] = (hex & 0x00500000) >> 22;
bits[21] = (hex & 0x00300000) >> 21;
bits[20] = (hex & 0x00100000) >> 20;
bits[19] = (hex & 0x00090000) >> 19;
bits[18] = (hex & 0x00050000) >> 18;
bits[17] = (hex & 0x00030000) >> 17;
bits[16] = (hex & 0x00010000) >> 16;
bits[15] = (hex & 0x00009000) >> 15;
bits[14] = (hex & 0x00005000) >> 14;
bits[13] = (hex & 0x00003000) >> 13;
bits[12] = (hex & 0x00001000) >> 12;
bits[11] = (hex & 0x00000900) >> 11;
bits[10] = (hex & 0x00000500) >> 10;
bits[9] = (hex & 0x00000300) >> 9;
bits[8] = (hex & 0x00000100) >> 8;
bits[7] = (hex & 0x00000090) >> 7;
bits[6] = (hex & 0x00000050) >> 6;
bits[5] = (hex & 0x00000030) >> 5;
bits[4] = (hex & 0x00000010) >> 4;
bits[3] = (hex & 0x00000009) >> 3;
bits[2] = (hex & 0x00000005) >> 2;
bits[1] = (hex & 0x00000003) >> 1;
bits[0] = (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.
What's the best way to go about this?
Thanks
for (int i=0;i<32;i++) {
bits[i]=hex&1;
hex>>=1;
}
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