1

Stupid question here:

I'm trying to convert a char array to a integer number. This is my case (extracted from main code, I've simplyfied it..):

int val;
char *buff;
uint8_t v1 = 2;
uint8_t v2 = 25;

buff[0] = v1;
buff[1] = v2;
val = strtol(buff, NULL, 16);

In that situation the val returns always '0' but, if I replace 'buff' with "0x225", it returns the expected value of 549.

What I'm doing wrong? Thanx in advance..

1
  • From your comments, it looks like you are receiving numbers as-is, no text representation (ascii) of it. If so, then you don't need strtol(), but can just join the uint8_t values to get your result. For little endian processors: val = (v2 << 8) | v1; Commented Jan 27, 2019 at 20:18

1 Answer 1

4

you need to learn C (C++ actually as arduino is programmed in C++).

strtol converts strings to numbers.

string in C is a array of char elements ending with zero (not '0' but 0). So "0x225" is the array of {'0', 'x', '2', '2', '5', 0}

'2' is not the number 2. It is ASCII representation of char '2' which is 50 in decimal.

buff[0] = '0';
buff[1] = 'x';
buff[2] = '2';
buff[3] = '2';
buff[4] = '5';
buff[5] = 0;

val = strtol(buff, NULL, 16);


buff[0] = 48;
buff[1] = 120;
buff[2] = 50;
buff[3] = 50;
buff[4] = 53;
buff[5] = 0;

val = strtol(buff, NULL, 16);

your code has many other issues. You need to understand what 25 and what 0x25 is (they are not equal). You should start from the book and PC compiler and learn language from the very basic stuff.

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I receive from the serial a set of values like the one described above. I know '2' is different from 2 but in my case what I receive is the number 2, wich I have to concatenate for obtain a hex number
Man, we are going to misunderstanding. Like I said, I've extracted this portion of code from a really big code and what I obtain from serial is this situation: [159922] Packet: 19 0 0 20 0 0 21 3 22 66 53 23 0 63 24 30 25 10 136 26 10 136 34 2 35 1 With a certain logic some numbers are IDs or data values. The data values are one or two bytes uint_8 that rapresent an hex value when concatenated. Hope I've clarifyed my first question. Regards
@Danny89530 "Man" : uint8_t v1 = 2; uint8_t v2 = 25; buff[0] = v1; buff[1] = v2; val = strtol(buff, NULL, 16); Follow my advice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.