Divide a string of 32 into 4 8 hex in c

Problems with the current code:

  • "4 strings of 8 chars each" is char in[4][8+1]; and not char in[8]. You need room for null termination.
  • 32 bits means iterate from 0 to 31, not from 0 to 32.
  • There's no need to copy byte per byte. It's slow and makes everything needlessly complicated.

This seems to be the requirements:

  • Split the original string in 4 sub strings.
  • Convert each sub string to an integer.
  • Display the result as hex

In which case you can simply iterate 4 times over the input string:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (void)
{
  const char* inst = "10101010101010101111111100111101";
  char in [4][8+1];

  puts("Bin      Hex");
  for(size_t i=0; i<4; i++)
  {
    memcpy(in[i], &inst[i*8], 8);
    in[i][8] = '\0';
    unsigned long val = strtoul(in[i], NULL, 2);    
    printf("%.8s %.2lX\n", in[i], val);
  }
}

Output:

Bin      Hex
10101010 AA
10101010 AA
11111111 FF
00111101 3D

The problem is your in is not NUL terminated.

Thus passing in to strol invokes the undefined behavior.

Do as below.

    unsigned char in[9]; //+1 to hold the NUL char.

     ....
    if (i%8 == 0 && i != 0) {
                in[8] = '\0'; //NUL terminate the string.
                unsigned char t = (unsigned char) strtol(in, NULL, 2);
                printf("%x \n", t);
    }

Tags:

C