Split a string and convert individual pieces to hexadecimal

96 views Asked by At

I have a string like "03FE" holding hexadecimal values. I need to split this string in two parts, and convert each individual part to the equivalent hexadecimal.

That is, I need 0x03 in one variable and 0xFE in another variable.

For example, if I didn't have to split the string, this is how I would have done it:

 char *p;
 uint32_t uv=0;
 uv=strtoul(&string_to_convert, &p, 16);

How shall I proceed if I needed to split the string?

2

There are 2 answers

0
barak manos On BEST ANSWER

Split the output of strtoul instead:

uint8_t uv_hi = uv >> 8;
uint8_t uv_lo = uv & 0xFF;
0
Sourav Ghosh On

I think

  • You can create one additional buffer of length n+1, where you want to split the string into n byte tokens
  • Use snprintf() to print out n characters to the temporary buffer.
  • Use strtoul() to convert the temporary buffer content to hex value.
  • Iterate over till you have tokens left.

This way, you can have a generic approach to tokenize and convert a source string of any length into tokens and then convert them to hex values.