简体   繁体   中英

Converting std::string of hexadecimal to std::array<T, 6>

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM