## Converting binary to hex

5 posts / 0 new
Author
Message

Hi guys

I'm writing a program (using an Atmel 324P) to output 16 address bus lines and 8 data bus lines as hex to an LCD. I've created the circuit diagram and while I wait for the components to arrive I'm writing the code for the AVR.

Part of the code I've written converts 4 bits at a time of the address/data lines and outputs the result as a single ascii character.

For example:

Address bus (coming in on Port A & Port B) = (A) 1110 0000 (B) 1111 0110

We take the most significant group of 4 bits: 1110 (binary) = 14 (decimal) = 'E' (string hex character)

The ascii code for 'E' is 69 and is sent to the LCD display

Do the same for each group of 4 bits

As I don't have all of the components for this project yet would someone mind commenting on/critiquing my code for performing the above conversion?

```char GetHexChar(int b3, int b2, int b1, int b0)
{
int n = 0;
char s[32];

// calc the decimal version of the 4 bit number
if (b0==1) n+= 1;
if (b1==1) n+= 2;
if (b2==1) n+= 4;
if (b3==1) n+= 8;

// return the hex version of the decimal value
if (n>=10) n+=35;
else n+=48;

// convert integer to ascii
itoa(n,s,12);

return(s[1]);
}
```

This topic has a solution.
Last Edited: Sat. Sep 13, 2014 - 08:55 PM

Actually, the following does the trick. It returns the ascii code which is then parsed to a shift register (by another routine) bit-by-bit which is connected to the LCD:

```int GetHexChar(int b3, int b2, int b1, int b0)
{
int n = 0;
//char s[32];

// calc the decimal version of the 4 bit number
if (b0==1) n+= 1;
if (b1==1) n+= 2;
if (b2==1) n+= 4;
if (b3==1) n+= 8;

// return the hex version of the decimal value
if (n>=10) n+=35;
else n+=48;

return(n);
}```

Last Edited: Sat. Sep 13, 2014 - 06:00 PM

Passing around four bits as four time 16 bit integers is not the most efficient method. You might want to look at how you handle the data in the code that calls this function.

you've got some magic numbers that make the code a bit obscure:

Rather than 48, use '0' that saves you looking up the ascii table

and 35 use ('A'-10) , besides, i think 35 is wrong as ascii A is 0x41 or 65 decimal minus 10 is not 35.

Itoa() with a base of 12 isn't going to be too useful. You could also look at printf/sprintf as well.

This reply has been marked as the solution.
```char GetHexChar(int input)
{
char output;
if (input >= 10)
{
output = (input - 10) + 'A';
}
else
{
output = input + '0';
}

return output;
}

//Usage
unsigned char temp = PORTB;
char upperNibble = GetHexChar(temp >> 4);
char lowerNibble = GetHexChar(temp & 0x0f);```

Regards,
Steve A.

The Board helps those that help themselves.