c_cpp 通过位操作获得无符号整数的补码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 通过位操作获得无符号整数的补码相关的知识,希望对你有一定的参考价值。

/*
A complement of a number is defined as the inversion (if the bit value = 0, change it to 1 and vice-versa) of all 
bits of the number starting from the leftmost bit that is set to 1. For example, if N = 5, N is represented as 101 
in binary. The complement of N is 010, which is 2 in decimal notation. Similarly if N = 50, then the complement 
of N is 13. Complete the function getIntegerComplement(). This function accepts N as parameter. The function should 
return the complement of N.The section of the program which parses the input and displays the output will be handled 
by us. Your task is to complete the body of the function or method provided, and to return the correct output.

Constraints :
0 ≤ N ≤ 100000.

Sample Test Cases: 

Input #00:
50

Output #00:
13

Explanation:

50 in decimal form equals: 110010 when converted to binary.
Inverting the bit sequence: 001101. This is the binary equivalent of decimal 13.

Input #01:
100

Output #01:
27

Explanation:

The bit sequence for 100 is 1100100. Inverting the sequence gives 0011011 which is the binary equivalent of decimal 27.
*/

// idea: generate a mask.
// eg: N =  00000000000000000000000000010001
            

int getIntegerComplement(unsigned int N) {  // eg:  N= 00000000000000000000000000010001
    if(N == 0) return 0;    
    unsigned int m = 1<<31;                 //      m= 10000000000000000000000000000000
    while((m&N) == 0)
        m >>= 1;                            // now  m= 00000000000000000000000000100000
    m <<= 1;                                // now  m= 00000000000000000000000001000000
    m -= 1;                                 // now  m= 00000000000000000000000000111111
    N ^= m;                                 // now, use XOR 1, since 1^1=0, 0^1=1.
    return N;                               // now  N= 00000000000000000000000000001110
}

以上是关于c_cpp 通过位操作获得无符号整数的补码的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 无符号整数的反转位

scala 基本类型和操作

原码 反码 补码

整数编码

使用 32 位无符号整数乘以 64 位数字的算法

查找无符号整数的补码