Re: help needed on coversin of an char array to an integer
- From: Willem <willem@xxxxxxxx>
- Date: Thu, 21 Feb 2008 13:35:03 +0000 (UTC)
MAx wrote:
) Hi,
) Im kinda stuck in a project at a point where i need an array to
) be converted to a
) integer using some kind of math.
) This board does not support functions like scanf, sscanf etc as
) it does not have enough memory to hold their stack.
)
) given a string char str[8] = {'0', '0', '0' , '1' , 'f' , 'b' ,
) 'c' , 'a' };
) i need a function which can convert this array to an integer
) ( 0x0001fbca )
Since you're talking about a 'board' I assume that you have a single,
fixed platform, and that your character set is ASCII.
I also assume that char is 8 bits and unsigned long is at least 32 bits,
that you will never have malformed input, and that you want a lean and
mean solution.
This makes the following (quite evil) code possible:
unsigned long hex2num(unsigned char str[8])
{
unsigned long *res, dig;
res = (unsigned long *)str;
dig = ((*res & 0x10101010) >> 4) * 0x0f;
*res = (*res & dig) | ((*res + 0x09090909) & (dig ^ 0x0f0f0f0f));
res = (unsigned long *)(str + 4);
dig = ((*res & 0x10101010) >> 4) * 0x0f;
*res = (*res & dig) | ((*res + 0x09090909) & (dig ^ 0x0f0f0f0f));
return (str[7] ) + (str[6] << 4)
+ (str[5] << 8 ) + (str[4] << 12)
+ (str[3] << 16) + (str[2] << 20)
+ (str[1] << 24) + (str[0] << 28);
}
Which should translate nicely into assembly.
(The last bit with the return might be sped up a bit, still).
As an exercise to the reader: How many assumptions does this
code make that are outside the C standard ?
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
.
- References:
- Prev by Date: Re: compare two float values
- Next by Date: Re: C90 IDE+compiler for Windows / educational purposes
- Previous by thread: Re: help needed on coversin of an char array to an integer
- Next by thread: Re: help needed on coversin of an char array to an integer
- Index(es):
Relevant Pages
|