Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: changing hex to decimal

2009-08-04 by Don Kinzer

--- In AVR-Chat@yahoogroups.com, "aligole_2005" <aligole_2005@...> wrote:
> in fact I want to have the c code of the function that gives
> a char or string hex data and give me the decimal data.
The suggestion to use strtoul() may work but you should note that it requires that the string have a 0x prefix if it is hexadecimal.  From your description, I take it that the prefix does not exist and would have to be added.

The scanf() suggestion is also useful but you may find that using it add a *lot* of code to your application due to its generality.

The algorithm for converting from hexadecimal characters to the corresponding value is very simple.

1) Initialize the value accumulator to zero
2) For each character of the sequence: if the character is '0' (0x30) through '9' (0x39), subtract 0x30 from the character and add the result to the accumulator after having multiplied the accumulator by 16; if the character is 'A' (0x41) through 'F' (0x46), subtract (0x41 - 10) from the character and add the result to the accumulator after having multiplied the accumulator by 16.
3) The numeric value of the hexadecimal sequence is in the accumulator.

If you need to also accept hexadecimal characters 'a' through 'f' it is simple to extend step 2 for those characters.  Also, you need to decide what to do when you encounter a character that is not a valid hexadecimal character or if too many hexadecimal characters are present given the size of the accumulator.

Don Kinzer
ZBasic Microcontrollers
http://www.zbasic.net

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.