Search code examples
c++bittwos-complementones-complement

Why does 0xff equal to negative 0 in C++


I saw some code looking like this:

Object *area = new Object[n];
memset(area, 0xff, sizeof(Object) * count);

So this fills the Object array's every field with bit 1. Then later there are multiple places checking if an object's field has not been filled yet by checking against ~0 (negative zero):

const unsigned int NULL_INDEX = ~0;
...
if(object.field == NULL_INDEX) {...}

The field on that Object class is unsigned int type. I'm confused that why 0xff can be evaluated to be equal to ~0, on unsigned int? I saw another post talking about 0xff equals -1 on 2's complement system, and found another post which I think it means that whether a C++ program interprets 0xff to be -1 or ~0 is system dependent?

What exactly is the portable way in C++ to check for integer when filled with 0xff? Should this be checked against unsigned int or signed int? I'm so confused...


Solution

  • ~0
    

    Just sets all the bits to 1. For example, if you have 32bit int and you use

    int all_the_ones = ~0;
    

    then you'd get 11111111111111111111111111111111 in the part of memory containing the value of all_the_ones

    0xff sets 8 bits to 1, so for a 32bit int it would be 00000000000000000000000011111111

    Anyway, for 0xff to be equal to ~0 on an int, the int in question would need to be 8bit/1byte, aka char

    unsigned char a = ~0;
    signed char b = ~0;
    

    Would give a equal to 255 and b equal to -1

    In memory they're both 11111111

    I don't understand why you'd want to know if 0xff was stored in an int, but comparing against a or b above should work.