Setting least significant bit of a pointer to 0

This question already has an answer here:

  • How do you set, clear, and toggle a single bit? 26 answers

  • First you have to make sure to use an integer type that has the same size as a pointer. On most 64-bit platforms, int s are 32-bit and pointers are 64-bit, so you'll corrupt the pointer when casting to an int . size_t usually does the job, except for some exotic memory models.

    Then I'd recommend to use a union which allows to modify the bits of a pointer without any casts:

    union {
        size_t *pointer;
        size_t  integer;
    } u;
    
    u.pointer = next_chunk;
    u.integer &= ~1;
    next_chunk = u.pointer;
    

    As others have already noted, you can clear bits of an integer by ANDing with the bitwise negated bit pattern which is 1 in case of the least significand bit.


    Setting least significant bit which starts at bit position 1 to value 0 works as follows.

    n &= ~((0x01) << 1)
    

    I think the code in the snippet in question is is not used properly.


    Try the following

    n &= ~0 << 1;
    

    The other way is

    n = ( ( unsigned int )n >> 1 ) << 1;
    

    Take into account that converting a pointer to an object of type int is unsafe.

    If you mean to set the least significant bit of the object pointed to by the pointer then the operation will look like

    *next_chunk &= ~0 << 1
    *next_chunk = ( *next_chunk >> 1 ) << 1;
    
    链接地址: http://www.djcxy.com/p/28800.html

    上一篇: 你怎么能在c ++中检查一个单独的二进制数字

    下一篇: 将指针的最低有效位设置为0