I want to create a program that converts integer number to a binary array and than put this into one byte variable.
I am working with itoa function, and it gives me strange results:
If I try number=3 it gives me 11 which is ok, then if I try number =2 it gives me 11, so something is not right, I would really appreciate the help. Thank you
Binary array holds ASCII representation of your number so butWrite is confused. So 0 is coded as 48 and 1 as 49. You need to subtract the char representation of '0' in your bitset
Also your array with only 3 usable positions is pretty short for a binary representation of a byte - careful on what value is or atoi will overflow your buffer
Last you should take into account where the \0 is in the binary array because anything past that is -possibly garbage not related to your value
Also your array with only 3 usable positions is pretty short for a binary representation of a byte - careful on what value is or atoi will overflow your buffer
While this works, That's not a "good" way to solve it in general case.
As mentioned you don't check for the end of the string you get from itoa. For example value of 1 will be transformed in the string "1" and coded into your array binary array as '1' in position 0 and '\0' in position 1 and the rest of the array will be left unmodified by the itoa function. As you force read position 1 and 2 that do not hold relevant values you generate a wrong output.
So what you want to do is do the bitwrite thingy only up to the '\0' char.
And of course you don't need to go to ASCII to get the binary representation of your number
And you thought, just ignore all the counter questions?
But what you do is absolutely useless. It's a full circle. It's going from a binary representation to a ASCII representation and back to binary again... Up to 8 number and value are exactly the same!
Just do Serial.println(number, BIN).
Or add it to your program and see for yourself
void setup() {
Serial.begin(115200);
}
void loop() {
for(int i=0; i<8;i++){
char binary[4] = {0};
byte value=0b00000000;
int number=i;
itoa(number,binary,2);
if(number>3){
bitWrite(value,2,binary[0]-'0');
bitWrite(value,1,binary[1]-'0');
bitWrite(value,0,binary[2]-'0');
}
else if (number>1){
bitWrite(value,1,binary[0]-'0');
bitWrite(value,0,binary[1]-'0');
}
else {
bitWrite(value,0,binary[0]-'0');
}
Serial.println("binary");
Serial.println(binary);
Serial.println(value,BIN);
Serial.println("Skip all the crap and just print");
Serial.println(number, BIN);
}
}
PS, watch your indentation. Your code is all over the place! press ctrl+T and see how much better it is