HEX to Binary Conversion

I'm trying to get my arduino to output a hex number in binary on LED's and it works for 0-9 but when I enter in letters it starts from 1 again on the LED's. I can't seem to figure out how to get it to display a through f in binary. Any help would be appreciated. Thanks

My code

int val;

void setup() {
  Serial.begin(9600);
  //set pins to outputs
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  
}

void loop() {

  
  while(Serial.available() > 0){
    //read value entered
    val = Serial.read();
    
    //check if hexadecimal
    if(isHexadecimalDigit(val)){
      Serial.printf("Enter a single HEX character: ");
      Serial.write(val);
      Serial.printf("\n");
      //turn on LED's corresponding to number 
      digitalWrite(4, (val & B0001));
      digitalWrite(5, (val & B0010));
      digitalWrite(6, (val & B0100));
      digitalWrite(7, (val & B1000));
      
    }else{
      //if number entered is invalid
      Serial.printf("Enter a single HEX character: ");
      Serial.write(val);
      Serial.printf("\nINVALID RESPONSE, Please try again.\n");
     //reset LED's to off
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
    }
  }
}

Is it possibly because the letters are being converted to their ASCII value rather than a hex number when you enter them in the serial terminal?

The information coming in on the Serial object is ASCII chars. I you enter a '1', you are actually reading an ASCII numeric value of 49. For digit characters 0 - 9, you can subtract '0' to get the numeric value (e.g., '1' = 49 - '0' = 49 - 48 = 1). If the value is greater than 58, do a toupper() on it and subtract 55 (i.e., if val = 'A', 65 - 55 = 10). If the value is 10-15, it's a hex digit.

Thank you so much econjack. Managed to get it working with your help and some shower thoughts haha. It was taking them as ASCII characters and i modified it to show the binary, hex, and decimal values as well as output to the LED's

You can not use built in Serial port window from Arduino IDE for this.
It shows all characters only as ASCII.

ASCII representation of long number for example is "182735478909" (11 bytes)
whine binary format of the same is 4 bytes.

So use some more advanced RS232 terminal such as http://docklight.de/
Or some other similar terminal software.

There (at least I know for docklight) you can see data in ASCII or HEX or binary format and send data in any format from PC side.

And also make predefined macro packets for sending to Arduino in any format. And many more things.

Its scripting is very powerful so you can basically react to data coming to PC from Arduino, process that data and bring back answer.

But for your dilemma data view in ASCII or HEX or Binary is most important for this dilemma :slight_smile: