Why doesn't C have unsigned floats?

后端 未结 12 1654
名媛妹妹
名媛妹妹 2020-11-28 01:47

I know, the question seems to be strange. Programmers sometimes think too much. Please read on...

In C I use signed and unsigned integers a

12条回答
  •  野性不改
    2020-11-28 02:08

    IHMO it's because supporting both signed and unsigned floating-point types in either hardware or software would be too troublesome

    For integer types we can utilize the same logic unit for both signed and unsigned integer operations in most situations using the nice property of 2's complement, because the result is identical in those cases for add, sub, non-widening mul and most bitwise operations. For operations that differentiate between signed and unsigned version we can still share the majority of the logic. For example

    • Arithmetic and logical shift need only a slight change in the filler for the top bits
    • Widening multiplication can use the same hardware for the main part and then some separate logic to adjust the result to change the signness. Not that it's used in real multipliers but it's possible to do
    • Signed comparison can be converted to unsigned comparison and vice versa easily by toggling the top bit or adding INT_MIN. Also theoretically possible, it's probably not used on hardware, yet it's useful on systems that support only one type of comparison (like 8080 or 8051)

    Systems that use 1's complement also just need a little modification to the logic because it's simply the carry bit wrapped around to the least significant bit. Not sure about sign-magnitude systems but it seems like they use 1's complement internally so the same thing applies

    Unfortunately we don't that luxury for floating-point types. By simply freeing the sign bit we'll have the unsigned version. But then what should we use that bit for?

    • Increase the range by adding it to the exponent
    • Increase the precision by adding it to the mantissa. This is often more useful, as we generally need more precision than range

    But both choices need a bigger adder to accommodate for the wider value range. That increases the complexity of the logic while the adder's top bit sits there unused most of the time. Even more circuitry will be needed for multiplications, divisions or other complex operations

    On systems that use software floating-point you need 2 versions for each function which wasn't expected during the time memory was so much expensive, or you'd have to find some "tricky" way to share parts of the signed and unsigned functions

    However floating-point hardware existed long before C was invented, so I believe the choice in C was due to the lack of hardware support because of the reason I mentioned above

    That said, there exists several specialized unsigned floating-point formats, mainly for image processing purposes, like Khronos group's 10 and 11-bit floating-point type

提交回复
热议问题