hex error

K

Keith Thompson

David Thompson said:
[...]
Note that any 2-digit string literal would do. If I were going to
use this approach, I'd probably omit the initialization and add
b[2] = '\0';
at the end. (I'd also assign to b[0] before b[1], but that doesn't
really matter.)
b[1] = (unsigned char)c / 16;
b[1] += (b[1] < 10)? '0': 'A';

b[0] = (unsigned char)c % 16;
b[0] += (b[0] < 10)? '0': 'A';
Maybe it's just me, but I'd (also?) put the more significant nibble in
b[0] and the less in b[1]. Or if that's what you meant, I don't think
you were clear about it. (Forest for trees maybe?)

I wasn't thinking about which nibble should go where, just that
assigning to b[1] first and b[0] second seemed odd.
 
L

luserXtrog

David Thompson said:
[...]
Note that any 2-digit string literal would do.  If I were going to
use this approach, I'd probably omit the initialization and add
    b[2] = '\0';
at the end.  (I'd also assign to b[0] before b[1], but that doesn't
really matter.)
    b[1] = (unsigned char)c / 16;
    b[1] += (b[1] < 10)? '0': 'A';
    b[0] = (unsigned char)c % 16;
    b[0] += (b[0] < 10)? '0': 'A';
Maybe it's just me, but I'd (also?) put the more significant nibble in
b[0] and the less in b[1]. Or if that's what you meant, I don't think
you were clear about it. (Forest for trees maybe?)

I wasn't thinking about which nibble should go where, just that
assigning to b[1] first and b[0] second seemed odd.

Yes. Attempted cleverness bites again.
I expect I'll do something stupid like this again, eventually.
But I will try to incorporate the following lessons.

* Don't do stuff in a funny order.
* Stop assuming ASCII encoding.
* Use library functions to avoid the need for assumptions
about encoding.

I think I was half-way planning for extensibility.
To convert a larger int to a string of hex nibbles,
you'd mod off the the least-significant piece and
then div down the remainder. And then it would be
simpler to fill the string right-to-left.

But the code I posted was indeed garbage.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,082
Messages
2,570,589
Members
47,212
Latest member
JaydenBail

Latest Threads

Top