ASCII to hex

Hey guys I am getting ASCII values in serial instead of hex values, and I donot want to mess up the transmitter circuit. So kindly give me suggestions how to change ascii to hex as soon as I get the values, or is it better to first save it and then change to hex. For example, I am getting 4C in ascii but i want 4C in hex.

Regards

See Serial Input Basics to receive correctly your Serial ASCII input and then use strtol() for example (or just go through the buffer and do the right maths, it's not rocket science 16 x the value of the high level character + the value of the low level character.

@OP
You have received these two ASCII frames for 4 and C: 00110100 (0x34) and 01000011 (0x43). Assume that you have saved them into these two variables: char x = 0x34 and char y = 0x43. You want to manipulate x and y so that you get a new hex value of 01001100 (0x4C) and save it into this variable: byte z = 0x4C.

J-M-L:
See Serial Input Basics to receive correctly your Serial ASCII input and then use strtol() for example (or just go through the buffer and do the right maths, it’s not rocket science 16 x the value of the high level character + the value of the low level character.

Apply the directives of the above quote, we get:
16 * 0x04 (the value of the high level character) + 0x0C (the value of the low level character)
==> 64 + 12
==> 76 (0x4C)

Sketch - A:(no use of Library Function)

void setup() 
{
  Serial.begin(9600);
  char x = 0x34;    //ASCII code of 4
  char y = 0x43;    //ASCII code of C

  byte x1 = x - 0x30; //get the value of high level cahrcater (4)
  byte y1 = y - 0x37; //get the value of low level charcater (C=12). Why to subtract 0x37? we do-no?

  byte z = (x1<<4) + y1;  //01000000 (16*4 = 64) + 00001100 (+12) = 01001100 (76) = 0x4C
  Serial.println(z, HEX);   //shows: 4C
}

void loop() 
{
  
}

BTW: The above sketch will not work for all kinds of charcaters. It is limited to: high level character: 0 - 9 and low level character: A - F.

Sketch - B:(use of the function: strtol())
Left as an exercise for the OP.

GolamMostafa:   char x = 0x34;    //ASCII code of 4   char y = 0x43;    //ASCII code of C

good example - may I suggest that for readability you could write directly

  char x = '4';
  char y = 'C';

then it's obvious that this represents the captured input

then to do the maths I would use also characters but understand you are trying to get OP to think. :)

(also nowadays, in sample code I feel we should push newbies to use 115200 at least in Serial.begin() rather than the very old legacy 9600)

J-M-L:
then it’s obvious that this represents the captured input

Cool! :slight_smile: