3

I'm working on an Arduino project and I want to store a hex value as string.

eg: Hex is C697C63B

for (byte i = 0; i < bufferSize; i++) {
     Serial.print(buffer[i], HEX);
}

I would like to store the String as x = "C697C63B";

  String CardID = "";
  for (byte i = 0; i < bufferSize; i++) {
    CardID += (buffer[i],HEX);
    Serial.println(CardID);
  }

But the Sting is stored as CardID = 16161616

Sorry I just start C++ for a week and I spend 3 day already just to find answer.

Okay i found the answer now thank you everyone that help

  String CardID = "";
  for (byte i = 0; i < bufferSize; i++)
    CardID += String(buffer[i], HEX);
  Serial.print(CardID);
user1437099
  • 41
  • 1
  • 2
  • 6
  • 2
    `CardID += (buffer[i],HEX);` doesn't do what you think it does. Read up on [comma operator](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work). In addition, you need to provide [mcve]. – Algirdas Preidžius Mar 17 '16 at 11:11

5 Answers5

2

You should use an ostringstream:

auto outstr = std::ostringstream{};
outstr << std::hex << 0xC697C63Bul;
auto myHexString = outstr.str();
cdonat
  • 2,748
  • 16
  • 24
0

std::ostringstream + IO manipulator hex may be want you want.

Youka
  • 2,646
  • 21
  • 33
0

You can use c-style sprintf :

char str[100];
sprintf(str, "%08x", HEX);
taarraas
  • 1,483
  • 9
  • 18
0
#include <stdio.h>

int main(void) {
  int nHex = 0xC697C63B;
  char pHexStr[100];
  sprintf(pHexStr,"%x",nHex);
  fprintf(stdout, "%s", pHexStr);

  return 0;
}
fandyushin
  • 2,350
  • 2
  • 20
  • 32
0

So simple in Arduino Programming Language to convert hex to be a string.

Just doing:

char StringValue[ ]=String(0xFF,HEX)
Hzzkygcs
  • 1,532
  • 2
  • 16
  • 24
  • Using ESP32, I receive a "array must be initialized with a brace-enclosed initializer" error message on compile. – Will Lovett Jun 24 '20 at 13:35