decimal to binary from serial inputted numbers

Dear forum

I have a litle question regarding the conversion from decimal to 8 bitbinary from numbers read from the serial port. When I use the code below , when I send the number 2 i get this output 00110010

Clearly this is wrong but the question is how do i make this whit the right output (00000010)

Thanks in advance and with best regards Ben

int incomingByte = 0; // for incoming serial data

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();

   for (int b = 7; b >= 0; b--)
  {
    Serial.print(bitRead(incomingByte, b));
  }
  Serial.println();
  }

Because you are sending an ASCII "2" not the number 2. The binary for ASCII "2" is 00110010 or 0x32 hex or 50 decimal. If you are only interested in converting single digit numbers you can just subtract 0x30. However, you should check to make sure a numeric character is entered and not an alpha character.

Because the number is in ASCII, you need to convert it to an int first. Suppose you get "123" in a char array named str[]. Then:

  • int number;*
  • number = atoi(str);*
  • Serial.print(number, HEX);*

will print the number in hex.

econjack:
Because the number is in ASCII, you need to convert it to an int first. Suppose you get "123" in a char array named str[]. Then:

  • int number;*
  • number = atoi(str);*
  • Serial.print(number, HEX);*

will print the number in hex.

ok that did the trick! thank you sir!

btw is it normal that my leading 0 will not show? For example when i input 3 i get 11 and not 00000011

Thank you verry mutch and with best regards Ben