-3

A 12 byte string which represents 6 hexadecimal values, needs to be converted to an std:array<uint8_t,6>. I am getting erroneous results from the hexadecimal conversions. I re-purposed some of the code over here for the Hex conversions from a string. Thank you for your time

Code

std::vector<std::array<uint8_t,6> > tracker =
  {
    { 0x66, 0x66, 0x66, 0x66, 0x66, 0x66 },
    { 0x99, 0x99, 0x99, 0x99, 0x99, 0x99 }
  };

std::array<uint8_t, 6> singular= { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 };

void setMac() {
  Serial.println("MAC TEST 1");
  std::string macInput = "121212121212";
  macTrans(macInput);

  tracker.push_back(singular);
  for (const auto& target : tracker)
  {
    printf("%02x:%02x:%02x:%02x:%02x:%02x\n", target[0], target[1], target[2], target[3], target[4], target[5]);
  }
}

void macTrans(std::string mac){
    singular = HexToBytes(mac);
}

std::array<uint8_t,6> HexToBytes(const std::string& hex) {
  std::array<uint8_t,6> bytes;

  for (unsigned int i = 0; i < hex.length() && i < 12; i += 2) {
    std::string byteString = hex.substr(i, 2);
    uint8_t byte = (unsigned char) strtol(byteString.c_str(), NULL, 16);
    if (i==0)
      bytes[0] = byte;
    else
      bytes[i-1] = byte;
  }

  return bytes;
}

Current Output:

MAC TEST 1

66:66:66:66:66:66
99:99:99:99:99:99
12:12:30:12:fe:12

Expected Output:

MAC TEST 1

66:66:66:66:66:66
99:99:99:99:99:99
12:12:12:12:12:12
Rice
  • 3,371
  • 4
  • 19
  • 23
  • 2
    Here is an answer: https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – 273K May 02 '19 at 05:37
  • Why does `macTrans` use a global variable rather than just returning the value? – Alan Birtles May 02 '19 at 06:14
  • @AlanBirtles Because this is an example snippet and the actual production code is embedded – Rice May 02 '19 at 15:12
  • Considering changing the title of the OP to: "Posting to SO at 2am: A Cautionary Tale" – Rice May 02 '19 at 16:48

1 Answers1

2

In HexToBytes, you're writing outside the array, and that has undefined behaviour.
(You are writing to positions 0, 1, 3, 5, 7, and 9.)

When you "repurposed" the code you found, you should have used division by two instead of subtraction by one.

Replace

if (i==0)
  bytes[0] = byte;
else
  bytes[i-1] = byte;

with

  bytes[i/2] = byte;
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Thank you. I wrote this post when I was burnt out of my mind and I appreciate the (albeit obvious) answer you posited here. – Rice May 02 '19 at 15:22