Page 1 of 1

Byte to Hex conversion & expressions in chr function

Posted: 12 Mar 2010 07:36
by jimMikroAVR
Hello,

I'm trying to convert a byte to a HEX in a string variable. I found some code in in the manual that will send the HEX string to the UART. I tried to convert this code but I need a way to convert a ASCII code stored in byte to a string. I wanted to use the CHR function but is seems it doesn't allow expressions. This is very strange to me! Support for expressions with the chr function has been in every version of BASIC I have used. Including the good old Commodore BASIC and even the lame TI 99!

dim i, bHi, bLo as byte
dim txtHex as string[2] 'new code
bHi = i and 0xF0
bHi = bHi >>4
bHi=bHi +"0"
if (bHi>"9") then
bHi = bHi + 7
end if
bLo = (i and 0x0F)+"0"
if (bLo>"9") then
bLo=bLo+7
end if

'code for example in manual
'UART1_Write(bHi)
'UART1_Write(bLo)

'What I would like to...
txtHex = chr(bHi) + chr(bLo)

Thanks for your time.

Jim

Re: Byte to Hex conversion & expressions in chr function

Posted: 12 Mar 2010 13:48
by foravr
Hi,
yes the good old times. Commodore basic also had the great 'val' function that could not only convert a string into a float but calculate a complex expression. With microbasic you have to go one step back and do things like print hex yourself. But the great basic compiler gives you all the possibilities:

Code: Select all

dim anybyte as byte
      txstring as string[2]

sub function nibble_to_hex(dim nibble as byte)as byte
if nibble < 10 then
   result = 48 + nibble            'ascii code 0...9
else
    result = 55 + nibble           'ascii code A...F
end if
end sub

main:
anybyte = 237                                                  'for instance

'if you want to print it:

uart1_write(nibble_to_hex(anybyte>>4))           'higher nibble
uart1_write(nibble_to_hex(anybyte and 15))      'lower nibble

'or if you need a string:

txstring[0] = (nibble_to_hex(anybyte>>4))
txstring[1] = (nibble_to_hex(anybyte and 15))
txstring[2] = 0
.end
...and the libraries are still growing.
foravr