Home > Net >  Converting stored binary data to hex?
Converting stored binary data to hex?

Time:12-22

char string[100] = "000000000000000000010000000000" this is the data i have and the data is in bits that 4 individual 8 bits that is when we split string[100] we get, 00000000 00000000 00000100 00000000 can anyone help me convert it to hex value using C language?

for the above string ,after converting it to hex we need to get " 00 00 04 00 " so similarly based on the input i need to get a desired output.

CodePudding user response:

No need to re-invent the wheel, just use strtol.

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

int main (void)
{
  char string[100] = "000000000000000000010000000000";
  printf("%.8lx\n", strtol(string,0,2));
}

It you need to group it as bytes with space in between:

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

int main (void)
{
  char string[100] = "000000000000000000010000000000";
  char byte_str[100];
  sprintf(byte_str, "%.8lx\n", strtol(string,0,2));
  for(size_t i=0; i<strlen(byte_str); i =2)
  {
    printf("%c%c ", byte_str[i], byte_str[i 1]);
  }
}

This might not be the most efficient code but it literally took me a few minutes to write.

CodePudding user response:

If it an exercise to learn how to convert and split number into bytes without fancy library functions:


unsigned convert(const char * restrict str)
{
    unsigned result = 0;
    while(*str)
    {
        result *= 2;
        result  = *str   == '1';
    }
    return result;
}

#define MASK ((1 << CHAR_BIT) - 1)
#define GETBYTE(val, index) (((val) >> ((sizeof(val) - (index) - 1) * CHAR_BIT)) & MASK)


void print(const unsigned val)
{
    for(int index = 0; index < sizeof(val); index  )
    {
        printf("x%c", GETBYTE(val, index), (index == sizeof(val) - 1) ? '\n' : ' ');
    }
}

int main (void)
{
  char string[100] = "000000000000000000010000000000";
  unsigned val = convert(string);
  printf("0xx\n", val);
  print(val);
}


https://gcc.godbolt.org/z/18G7r37TW

  • Related