Re:Should I Use Signed or Unsigned Ints? (Part 2)
by detrino on Tuesday September 01, 2015 @10:45PM
(#10157151)
I found this odd too. I'd add that comparison and right shift also differ, but signed right shift does have obvious semantics: sign extension. I'd also argue that signed division has obvious semantics: round towards negative infinity, which matches the semantics of right shift with sign extension. I'm saddened that none of C/C++/x86 have native support for this kind of division, it's _always_ what I want from signed division.
Re:Should I Use Signed or Unsigned Ints? (Part 2)
by dnautics on Wednesday September 02, 2015 @02:54AM
(#10157782)
>CPU vendors who actually implement undefined behavior are, in my opinion, nuts. Give the CPU a nice clean spec that fully defines what happens and stick to it.
So, basically none of the IEEE floats engines in AMD, Intel, ARM, etc....
Re:Should I Use Signed or Unsigned Ints? (Part 2)
by TorKlingberg on Wednesday September 02, 2015 @11:41AM
(#10159971)
This is why two's complement became dominant. It simplifies CPU design.
I find that part very strange. Here are a couple of observations:
* Unsigned wrapping binary addition and two's complement addition are identical as long as you don't try to report carry or overflow.
* Unsigned wrapping binary subtraction and two's complement subtraction are identical as long as you don't try to report borrow or underflow. If the goal is absolute simplicity, subtraction isn't needed at all because both cases are efficiently handled by two's complement negation (which is the same thing as calculating 0-x in an unsigned wrapping sense) followed by addition.
* Unsigned wrapping binary non-widening multiplication (the usual case) and two's complement multiplication are identical. This follows from the distributive law: an n-bit two's complement negative number -x is represented as 2^n - x. If you multiply -x (a two's complement number interpreted as unsigned) by y, you end up with (2^n - x) * y, which is y2^n - xy. The first term doesn't affect the result, because its low bits are all zero.
Widening multiplication is extremely useful, but implementing the unsigned version in hardware should make it fairly simple to emulate the signed version. x86 implements both.
Division is nasty, especially because number theorists and C programmers disagree on what it means when negative numbers are involved. Really simple CPUs don't implement division at all, though.
Finally, CPU vendors who actually implement undefined behavior are, in my opinion, nuts. Give the CPU a nice clean spec that fully defines what happens and stick to it.