1

I have to handle a String coming in over UART containing a bunch of information, part of it is a MAC-address that I get by using String.substring(a, b) returning a 12-char String representing a mac-address "B8C9A45BA770" <- (just an example).

I need the format of the mac-address to be a uint8_t array like so { 0xB8, 0xC9, 0xA4, 0x5B, 0xA7, 0x70 }.

So I need a function to convert a String to a uint8_t*. Sadly I have no clue how to convert this. There has so be an easy way right? its "C8" to 0xC8 and so forth...

Any ideas on this?

1 Answers1

2

Personally I'd go with a basic implementation such as this one.

const uint8_t MAC_length = 6;
uint8_t* MAC_buffer[6];

uint8_t fromHexChar(char c) { uint8_t result = 0 if ((c >= '0') && (c <= '9')) result = c - '0'; else if ((c >= 'A') && (c <= 'F')) result = 10 + c - 'A'; else if ((c >= 'a') && (c <= 'f')) result = 10 + c - 'a'; return result }

uint8_t* toMAC(String s) { for (uint8_t i = 0; i < MAC_length; i++) { MAC_buffer[i] = (fromHexChar(s.charAt(2i)) << 4) | fromHexChar(s.charAt(2i + 1)); } return MAC_buffer; }

Probably it can be optimized, but this is such a simple job and to be used so rarely that I think this is enough.

Important: I did not test this code, so there may be bugs inside.

If you need to start from an arbitrary point in the String instead of at the beginning, you simply have to modify it this way:

uint8_t* toMAC(String s, uint8_t startIdx)
...
        MAC_buffer[i] = fromHexChar(s.charAt(2*i + startIdx)) << 4 | fromHexChar(s.charAt(2*i + startIdx + 1));

Note for future me: I checked both on a simulator and in the code, and charAt is safe to use even when the index is outside the string boundaries (it simply returns 0).

frarugi87
  • 2,731
  • 12
  • 19