Decimal to binary converter

Hello,
I am working on a school project, for creating an arduino code to convert decimals to binary... i am a beginner and glad to have managed to create a working code. But there is on slight problem ... when i convert my number, 2 "1" appear in front of the value and i can't figure out where they're coming from :expressionless:
Example with number 5:
image

Thanks for your help, i have to hand this in next week .

Please post code, not pictures of code.
Please post results and expectations.

Did you mean '5'?

The result is as expected.

int incomingByte = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
// envoie une donnée sur le port série seulement quand reçoit une donnée
if (Serial.available() > 0)
{ // si données disponibles sur le port série
// lit l'octet entrant
incomingByte = Serial.read();

// renvoie l'octet reçu
Serial.print("Base 2 ->");
Serial.println((char)incomingByte, BIN);

}
}

My expectations are that it only gives "0101"
And it needs to work for any number from 1 to 9

Thought experiment for you... what should it print if you send it a letter, like 'x'?

Not my expectation.
'5' == 0x35 == 0b00110101

Well, 5 in binary is 0101 and thats what i would want it to give for this example if you see what i mean :smile:

I don't know...

Try. Hint - do computer keyboards have only numbers on them? How do you suppose that 'x' would be transmitted?

There is 5 and there is 5.

sends out 1111000

...like the 'x' in the right hand column of the chart above?

yep

Now look up '5'.

What code do you get printed for 0 (zero).

Ok, I will try that tomorrow, thanks :+1:

1 Like

hi @louis_f

Change this line of your sketch: "Serial.println((char)incomingByte, BIN);"

with this line: Serial.println((incomingByte & 0x0F), BIN);

and test to see if is what you want.

RV mineirin

Or even

Serial.println(incomingByte - '0', BIN);

or even

if ( isdigit(incomingByte) ) {
Serial.println(incomingByte - '0', BIN);
} else {
Serial.println(F("out of range - not numeric input") );
}

this one will print garbage values for inputs (:, ;, <, =, >, ?) :

Serial.println((incomingByte & 0x0F), BIN);

just as subtraction will print garbage values for any non-numeric character.

Only decimals must be converted.

RV mineirin