Greetings from Pennsylvania.
On playing with pointers I get odd results that I do not understand. Perhaps you all can understand the problem. This is the code and attached are the results. Thanks for looking.
#define print Serial.print #define printf Serial.println void setup() { Serial.begin(9600); } void loop() { int iValue = 1025; // .... .... 00000100 00000001 int *iPtr = &iValue; char *cPtr; cPtr = (char*)iPtr; //typecasting print(" *iPtr "); printf(*iPtr); // should be 1025 - okay print(" *cPtr "); printf(*cPtr); // should be 1 at first byte; got inverted L print(" *(cPtr+1) "); printf(*(cPtr+1)); // should be 4 at second byte; got flipped L print(" atoi(*cPtr) "); printf(atoi(*cPtr)); // should be ascii value of odd char 1 print(" atoi(*(cPtr+1)) "); printf(atoi(*(cPtr+1))); // should be ascii value ofaodd char 2 delay(1000); }
I'm a newbie, can't research now but I like the problem. My guess is the define statements or mixed data types assigned to variable issue. I'll be back!
I think it may be more useful to ask this question:
Why do you think the output is wrong?
What do you think atoi does?
hint: look up the description of atoi.
The one who has the most fun, wins!
@harrya
I think that your problem is that you are assuming that the '1025' is stored as a series of characters instead of the binary value that yo originally stored there. So the value stored at the location iValue is 10000000001 binary or 401 hex.
You must remember that the value stored in a computer depends on the type of value stored and you must extract and process it according to the form it was loaded. So here, the value 1025 its stored as a binary value and you are trying to interpret the bytes at that location as a character string
Anything seems possible when you don't know what you're talking about.
I got this from the Arduino site. This is a lengthy discussion on the problem. I still don't understand it but I can see where I would like to parse an array for a bit and act on that bit then put it back, or do the same with a byte or a character.
https://forum.arduino.cc/t/strings-pointers/657671
This site is great, but you might want to watch this video on using pointers. Just an FYI
A better way to do this is to use codeblocks or some other ide that lets you look into memory location so you can see what is stored and how it is stored.
That way you can go to the pointer address itself
-----
Anyways ....
You assigned an int pointer to a character pointer which is ok.
But now the char pointer is now pointing at an 8 bit value.
If that value is below 32 that is a control character and is a non-printable ascii value.
unsigned char *cPtr works.
As for the atoi() it will not. I was thinking that the odd characters would have some ascii value but no.
Thanks for your inputs.