Interesting code bug at work

Oct 17, 2008 14:55

I just fixed a bug at work that formed an interesting puzzle. We have a quick printf function at work that handles formatting certain data types faster than microsoft printf (which is really slow). This code:

printf("%d", -2147483648)

produced this result:

-(

See if you can figure out why!

Leave a comment

Comments 5

(The comment has been removed)

jzig October 18 2008, 01:10:45 UTC
Nah, it's all integer stuff. Oh, and that specific number is the only one that failed, all other numbers work.

Reply


kvance October 18 2008, 02:51:16 UTC
I think it went something like this:

The printer sees the negative bit, so it prints a '-' and then negatizes the number.
Being -2^31, this doesn't go well. Now besides being the wrong number, it's still negative.
So when it's time to calculate the ASCII code of the first digit by adding it to ASCII '0', subtraction is performed instead, going to ASCII '('.
Then it divides by 10, checks if it's still > 0 (oops, nope, it's negative!) and stops printing.

Reply

kvance October 18 2008, 03:01:38 UTC
When I was writing that, I was thinking "negatize... there must be a better word for that." I suppose some people might say "negate" ;)

Reply

jzig October 18 2008, 03:10:10 UTC
Yup, kev wins the prize! Negating -2^31 and assigning the value to a signed 32 gives you... -2^31 it turns out :)

The other satisfactory answer is "because -( looks like a sad cyclops"

Reply

kvance October 18 2008, 03:16:42 UTC
Heh. Sad cyclops is totally what I would have guessed next.

Reply


Leave a comment

Up