View previous topic :: View next topic |
Author |
Message |
sorasit46
Joined: 07 May 2007 Posts: 69
|
How to write code for convert 2,B,C --> 2BC ? |
Posted: Sat Dec 11, 2010 8:37 pm |
|
|
2,B,C = Hex. Value ( Dec. = 700 )
How to write code for convert 2,B,C --> 2BC ?
regards |
|
|
gpsmikey
Joined: 16 Nov 2010 Posts: 588 Location: Kirkland, WA
|
|
Posted: Sat Dec 11, 2010 9:17 pm |
|
|
Assuming you mean you have those characters in a buffer of some sort, see the functions atoi(), atol() and atoi32() in the compiler manual - they convert a null terminated string into a number.
mikey _________________ mikey
-- you can't have too many gadgets or too much disk space !
old engineering saying: 1+1 = 3 for sufficiently large values of 1 or small values of 3 |
|
|
andrewg
Joined: 17 Aug 2005 Posts: 316 Location: Perth, Western Australia
|
|
Posted: Sun Dec 12, 2010 2:40 am |
|
|
atoi, atol and atoi32 all require a "0x" in the buffer to decode hex data. That might be OK, maybe not...
strtol/strtoul support a radix argument.
Or, you can do the conversion yourself. It helps to break the problem down into two steps:
1. Convert ASCII character to number: Code: | if (c >= 'A' && c <= 'F') v = c - 'A' + 10;
if (c >= '0' && c <= '9') v = c - '0'; | 2. Accumulate numbers into a total:How to handle invalid characters is up to you. The above is just an example. _________________ Andrew |
|
|
gpsmikey
Joined: 16 Nov 2010 Posts: 588 Location: Kirkland, WA
|
|
Posted: Sun Dec 12, 2010 5:31 am |
|
|
Well, I'm glad to see Andrew was more awake than I was - I started looking for scanf() and realized we don't have that. His approach is probably the best unless you want to create a buffer with "0x" in it then append the character string. You also may want to consider how to handle a backspace
for example if these numbers are being entered from a keyboard.
mikey _________________ mikey
-- you can't have too many gadgets or too much disk space !
old engineering saying: 1+1 = 3 for sufficiently large values of 1 or small values of 3 |
|
|
sorasit46
Joined: 07 May 2007 Posts: 69
|
|
Posted: Sun Dec 12, 2010 9:46 am |
|
|
Thanks for the help! |
|
|
|