0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Randomly Named User
  • 1,889
  • 7
  • 27
  • 47
  • There is no such thing as a "hexa variable". The variable contains an integer. The "hexadecimal" part is just way to present that integer to humans, as a string. The integer itself is not hex. – unwind Jun 10 '15 at 06:11

2 Answers2

5

Split the output of strtoul instead:

uint8_t uv_hi = uv >> 8;
uint8_t uv_lo = uv & 0xFF;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
barak manos
  • 29,648
  • 10
  • 62
  • 114
1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261