3

I have an array of 1's and 0's in C.

int foo[8];

int main()
{
  int i = 0;
  for (i; i < 8; i++)
  {
      foo[i] = 0;
  }

 foo[1] = 1;
 foo[3] = 1;
}

So, my array now is something like this:

01010000

And I want to convert this bin representation of my array to hex number. In this case it will be 0x50.

Is there any fast and easy way to do this?

Ken White
  • 123,280
  • 14
  • 225
  • 444
JohnDow
  • 1,242
  • 4
  • 22
  • 40
  • 1
    Group 4 elements, compute the decimal value and look the corresponding digit in a lookup table. – Mihai Maruseac May 14 '14 at 21:42
  • @aglasser I am not asking for string, but for array – JohnDow May 14 '14 at 21:48
  • A string in C is represented as an array of characters terminated with a NULL byte. A string **is** an array. – aglasser May 14 '14 at 21:49
  • @aglasser So, it is a good idea to convert int array to char array? – JohnDow May 14 '14 at 21:50
  • 1
    No, you don't need that conversion. – Mihai Maruseac May 14 '14 at 21:52
  • 1
    Converting from int to char is trivial, but I don't see how it is any different here. You can easily adapt the code given for an int array or a char array. Modify the `do...while` to another for loop that just increments i instead of incrementing the a pointer. int b = *a=='1'?1:0 is just assigning an int value to b whether *a (the current char) is a 1 or 0. Trivial to implement with ints. [Post in question is here.](http://stackoverflow.com/a/5307692/2599996) – aglasser May 14 '14 at 21:54
  • I've rolled back your edit. Altering your question to add the solution is not how StackOverflow works. Please see [Can I answer my own question?](http://stackoverflow.com/help/self-answer) for the proper way to do so. Thanks. – Ken White May 14 '14 at 22:42
  • What do you mean a hex number? Print it out in hex, or a string of hex rep? – SwiftMango May 14 '14 at 22:56
  • I think I'd be using `int value = 0; for (i = 0; i < 8; i++) value = (value << 1) | foo[i];` to get the integer corresponding to the binary digits. This can then be formatted to `0x50` with `char hex[10]; snprintf(hex, sizeof(hex), "0x%.2X", value);` (or just use `printf("0x%.2X\n", value);`, of course). – Jonathan Leffler May 14 '14 at 22:57

1 Answers1

0

Something like this, for some adaptability?

int start = 0, size = 4, i, value = 0;
for (i=start;i<size+start;i++) {
    value *= 2;
    if (foo[i] == '1') {
        value ++;
    }
}

Simple modular arithmetic. value is going to end up as 0-15, which you can easily convert to a hexadecimal character, and iterate the loop to collect as many hex digits as needed/available.

John C
  • 1,931
  • 1
  • 22
  • 34