How to convert char array to int

i have char array "0C" i want to convert into 0x0c , i try "atoi" but its not working

Is the char array terminated with a zero to turn it into a C style string , which is what atoi() expects ?

Please post what you tried

atoi() expects base 10, not base 16 ➜ use strtol() and say you are reading something in base 16

1 Like

when i try "12" atoi return int 12. but when i try "0C" atoi return only 0.

read post #3 again...

try this

char data[] = "0C";

void setup() {
  Serial.begin(115200);
  long dataValue = strtol(data, nullptr, 16); // you coudl use an end pointer instead of nullptr to know if something went wrong
  Serial.print("I read 0x"); Serial.println(dataValue, HEX);
}

void loop() {}

its working .
char d3[]="00";
int reg3=(int)strtol(d3,NULL,16);
but this function also convert 0c to 12 , i want "0c" to 0c as its.

your variable will hold a value. This is 12 in decimal or C in hexadecimal... it's the same value, it's just a different way of printing it.

To see it in hexadecimal use
Serial.println(value, HEX);

To see it in decimal use
Serial.println(value);
or
Serial.println(value, DEC);

to see it in binary use
Serial.println(value, BIN);

if you want leading 0, you have to deal with it yourself has the print function won't add that for you.

byte value = 0x0C;
if (value < 0x10) Serial.write('0');
Serial.println(value, HEX);
1 Like

thank , but i pass the value into array like.
outgoing.data.uint8[2] = reg3;
its oky or i want to do something to convert reg3 variable.?

It is okay. The 'reg3' variable contains the binary data. That is what you want, so you can use it as it is.

I made a variation. Suppose that there is a text with 8 hexadecimal numbers in it. Then I would use ssprintf() scanf() :

char text[] = "0C12D4436F000E5A";

void setup() 
{
  Serial.begin(115200);
  Serial.println( "Extract eight numbers from hexadecimal text");
  
  int x[8];
  sscanf( text, "%02X%02X%02X%02X%02X%02X%02X%02X", 
    &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7]);
  
  for( int i=0; i<8; i++)
  {
    if( x[i] < 0x10)
      Serial.print( "0");
    Serial.print( x[i], HEX);
    Serial.print( " "); 
  }
  Serial.println();
}

void loop() {}

Did you mean sscanf() or maybe sprintf() ?

1 Like

it's OK, yes. The value is the value (you have 8 bits really in memory). The way you interpret and print those 8 bits is just a user interface stuff. the bits are the same regardless of the base you want to print that out, the screen representation is different

1 Like

Oops, sorry, I meant sscanf(). The sketch was tested and works.

@J-M-L really thanks. problem solve. :slightly_smiling_face:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.