 # Problem converting char arrays to int/byte.

I get various answers converting char arrays to int/byte.

conversion problem.txt (767 Bytes)

https://forum.arduino.cc/index.php?topic=511893.0

Double post. And I think we have a new winner for most useless opening post. I'm not sure what the OP could possibly think we can do from what he wrote.

Haha!
Some code examples:

``````    char buf;
buf = '1';
buf = '9';
buf = '2';
buf = '\0';
int b = int(buf);
Serial.println(b, DEC);
==> in serial monitor: 2282

char buf;
buf = '1';
buf = '9';
buf = '2';
buf = '\0';
int b = atoi(buf);
Serial.println(b, DEC);
==> in serial monitor: 192

char buf;
buf = '1';
buf = '9';
buf = '2';
buf = '\0';
byte b = byte(buf);
Serial.println(b, DEC);
==> in serial monitor: 236

char IP = "192.168.0.103";
char buf;
for (int i = 0 ; i++ ; i < 3) buf[i] = IP[i];
buf = '\0';
byte b = byte(buf);
Serial.println(b, DEC);
==> in serial monitor: 240
``````

buf is an array. buf is a pointer to the first byte element of buf.

OK, so I have a fundamental misunderstanding of the workings of arrays. The Arduino reference guide does not adequately explain this. Can you point me to a good reference guide?

C++ arrays

ripetomato:
I get various answers converting char arrays to int/byte.

You get three wrong answers, when you do stupid stuff, and one correct answer when you do it right. What is the problem?

You do not necessarily have fundamental misunderstanding of arrays.

But you have a misunderstanding how to convert the text representation of a number to the number; you can not use a cast.

Look at atoi() and strtol().

Pointers pheew!!
I just had a confidence boost, starting to understand pointers. And discovered C++shell!
These reworked code examples actually work.
Thank you all!

``````#include <iostream>
using namespace std;
int main ()
{
char buf;
char * p;
p = buf;
*p = '1';
p++;  *p = '9';
p++;  *p = '2';
p++; *p = '\0';
int b = atoi(buf);
cout << "b=" << b;
return 0;
}
on execution: b=192

#include <iostream>
using namespace std;
int main ()
{
char buf;
char * p;
p = buf;
*p = '1';
*(p+1) = '9';
*(p+2) = '2';
*(p+3) = '\0';
int b = atoi(p);
cout << "b=" << b;
return 0;
}
on execution: b=192

//extracting the first byte from an IP address

#include <iostream>
using namespace std;
int main ()
{
char IP = "192.168.0.103";
char buf;
int i = 0;
while((IP[i] != '.')&&(IP[i] != '\0')){
buf[i] = IP[i];
i++;
}
buf[i] = '\0';
int b = atoi(buf);
cout << "b=" << b;
return 0;
}
on execution: b=192
``````