Hi All,
My main intension of is to convert the Hexstring stored in a char* into hex and then prefixing it with "0x" and suffix it with ','
This has to be done for all the hexstring char* is NULL.
Store the result prefixed with "0x" and suffixed with ',' in another char* and pass it to another module.
I just want to print and see the values in the result char* to see if it is stored as 0x30, (say when the input char* a = "30" )
How can I verify the values stored in the char*...?
I cannot print it neither as %s nor %x both gives junk values.. %s gives junk because it is hex and %x gives junk because i have formatted with "0x30," i think.. But am not clear and don't know how to check if the values got stored in this format. 0x30,
- Thanks
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int hexstr2bin(const char *hex_input, char *buf_output, size_t len);
static int hex2byte(const char *hex);
static int hex2num(char c);
main()
{
int len;
char* buf;
const char* hex ="abcd1234567890";
buf = (char*)malloc(100);
len = strlen(hex);
hexstr2bin(hex,buf,len);
printf("Values in hex %s",buf);
}
int hexstr2bin(const char *hex_input, char *buf_output, size_t len)
{
size_t i;
int a;
const char *ipos = hex;
char *opos = buf;
char *prefix = "0x";
for (i = 0; i < len; i++) {
a = hex2byte(ipos);
if (a < 0)
return -1;
*opos++ = prefix[0];
*opos++ = prefix[1];
*opos++ = a;
*opos++ = ',';
ipos += 2;
}
return 0;
}
static int hex2byte(const char *hex)
{
int a, b;
a = hex2num(*hex++);
if (a < 0)
return -1;
b = hex2num(*hex++);
if (b < 0)
return -1;
return (a << 4) | b;
}
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}