Binary string to decimal integer

bits array to int

The bits array can be converted to int and string string, but vector<bool> saves space. The length of bits should be less than the length of int, that is, less than or equal to 31 bits, and the highest bit is the sign bit.
If it is an unsigned binary string, the function return type is unsigned int, the highest bit is operated without judgment, and the maximum length of the bits array is 32 bits

//二进制转10进制
int bits_to_int(vector<bool>bits){
    
    
    int result=0;
    for(int i=0;i<bits.size()-1;i++){
    
    
        if(bits[bits.size()-1-i]){
    
    
        result+=pow(2,i);
        }
    }
     if(bits[0])//负数
     result=-result;
    
    return result;
}

It should be noted that whether the highest bit of a binary string is a sign bit depends on whether it is a signed number or an unsigned number, such as unsigned int, unsigned short, unsigned byte, etc. in C++. The highest bit of the binary string is not the sign bit, but int The highest bit of, short, byte is the sign bit, BYTE, WORD, DWORD in assembly are unsigned, SBYTE, SWORD, SDWORD are signed

Positive number (original code) to negative number (complement code):
the binary of the positive number is the original code, and the binary of the negative number is the complement. When a positive number is converted to a negative number, it is generally inverted +1, such as the original code of 5 0000 0101 to -5 , First negate: 1111 1010 (inverse code) and then +1: 1111 1011 (complement code)
Faster method: from right to left, the first 1 encountered, reverse all the left side of this 1, and the right side (including (Self) unchanged, that is, the original code of 5 is 0000 0101, the first 1 is the rightmost 1, then reverse the left, and the right remains unchanged: 1111 1011

Guess you like

Origin blog.csdn.net/weixin_42419611/article/details/106235855