0

Hi got this message which I need help with:

Severity Code Description Project File Line Suppression State Warning C4302 'reinterpret_cast': truncation from 'const _Elem *' to 'unsigned char' row 94

Severity Code Description Project File Line Suppression State Warning C4302 'reinterpret_cast': truncation from 'const _Elem *' to 'unsigned char' row 95

    uint16_t Id = 325;
std::stringstream stream;
stream << std::setfill('0') << std::setw(4) << std::hex << Id; //Result: 0145
std::string str1 = stream.str().substr(0, 2); //Result: 01
std::string str2 = stream.str().substr(2, 2); //Result: 45
unsigned char char1 = reinterpret_cast<unsigned char>(("0x" + str1).c_str()); //Wanted result: 0x01
unsigned char char2 = reinterpret_cast<unsigned char>(("0x" + str1).c_str()); //Wanted result: 0x45
unsigned char Mac[6] = { 0x00, 0x1D, 0xE2, 0x03, char1, char2 };
Fishfloat
  • 21
  • 1
  • You need to cast to `char*`. `char` is one character, for example 'a' whereas `char *` is a pointer to a character array which hopefully ends with `\0`. – Mustafa Ozturk Oct 05 '21 at 14:22
  • You need a function `unsigned char parse_hex(std::const std::string&)` instead of casting... – Jarod42 Oct 05 '21 at 14:23
  • 1
    Does this answer your question? [C++ convert hex string to signed integer](https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer) – wovano Oct 05 '21 at 14:25
  • `unsigned char char1 = ((str1[0] - '0') << 4) + (str1[1] - '0');`? – Jarod42 Oct 05 '21 at 14:26

1 Answers1

0

You are taking the very long way round: going from a number to a string, chopping that up, then re-parsing the string as a number...

Instead use simple bitwise operations:

unsigned char MSB = Id >> 8;
unsigned char LSB = Id & 0xFF;
unsigned char Mac[6] = { 0x00, 0x1D, 0xE2, 0x03, MSB, LSB };
Botje
  • 26,269
  • 3
  • 31
  • 41