Search code examples
cmemorylanguage-lawyertwos-complementmemset

Is two's complementary representation universally platform-independent?


it's idiomatic to initialize a block of memory to zero by

memset(p, 0, size_of_p);

when we want to initialize it to minus one, we can:

memset(p, -1, size_of_p);

no matter what type p is, because in two's complemenatry representation, minus one is 0xff for 8 bits integer, 0xffff for 16 bits, and 0xffffffff for 32 bits.

My concern is, is such two's complementary representation universally applicable in the realm of modern computers? Can I expect such code platform-independent and robust enough to port to other platforms?

Thanks in advance.


Solution

  • No, there are three schemes of representing negative numbers allowed by the ISO C standard:

    • two's complement;
    • ones' complement; and
    • sign/magnitude.

    However, you should keep in mind that it's been a long time since I've seen a platform using the two less common schemes. I would say that all modern implementations use two's complement.

    You only want to concern yourself with this if you're trying to be 100% portable. If you're the type of person who's happy to be 99.99999% portable, don't worry about it.


    See also info on the ones' complement Unisys 2200 (still active as at 2010) and this answer explaining the layouts.