[chbot] HEX and ANSII ATMEGA and Delphi

Volker Kuhlmann list57 at top.geek.nz
Mon Oct 26 06:12:20 GMT 2020

On Mon 26 Oct 2020 12:08:00 NZDT +1300, Marshland Engineering wrote:

> I think I have it all sorted except for itoa which is int and not unsigned
> int.

(You mean atoi()?)

The C standard requires standard functions, that includes itoa(), to
return a type of int. And that's signed (C standard default is signed,
if omitted).

> Can I modify my c libraries to make it unsigned or maybe just write my own
> function.

No, and no.

It's probably much simpler. The bit patterns of the value returned by
itoa() are the same, regardless of whether it might be signed or
unsigned. As it is signed, and you require unsigned, stick it into a
type cast and you're probably already done.

	unsigned int u;
	u = (unsigned int) atoa(...);

You can in theory leave out the cast in this case, but it's good practice
to put it there because it shows explicitly that you have thought about
the type mismatch, and you prevent a compiler warning (if it's enabled -
personally, I enable all warnings as usually they show the code is
either unclean or buggy).

You may have overflow issues to deal with if int is 32bit when you want
only 16bit. A clever extra cast might help you out there too.

The advantage of the casts are that they don't translate into extra

You could also try an expression like this (assuming you want 16bit):

	u = atoi() >= 0 ? atoi() : atoi() + 65536;

However if you need to convert a 4-digit hex string into a 16bit
unsigned int, you're most likely best off to make your own function.
Pulling atoi() into your program adds a lot more code than you need
because atoi() does other things too, unless you are calling it already

If run speed is a concern, also make your own function. Try a LUT for
speed/codesize tradeoff.

Or did I misunderstand the problem?



Volker Kuhlmann
http://volker.top.geek.nz/	Please do not CC list postings to me.

More information about the Chchrobotics mailing list