Fast way to convert a binary number to a decimal number

前端 未结 5 1713
感情败类
感情败类 2021-02-05 17:29

I have to convert a binary number like for example unsigned int bin_number = 10101010 into its decimal representation (i.e. 170) as quickly as possible

5条回答
  •  没有蜡笔的小新
    2021-02-05 18:20

    If you know the number of binary digits that you're dealing with and it's always fixed and the binary number comes in a string (as it would if read from a file or stdin) at runtime (i.e. compile time conversion not possible) then you could adopt this approach:

    int to_binary( const char* c )
    {
        return ( ( c[0] & 1 ) ? 0x80 : 0x00 ) |
               ( ( c[1] & 1 ) ? 0x40 : 0x00 ) |
               ( ( c[2] & 1 ) ? 0x20 : 0x00 ) |
               ( ( c[3] & 1 ) ? 0x10 : 0x00 ) |
               ( ( c[4] & 1 ) ? 0x08 : 0x00 ) |
               ( ( c[5] & 1 ) ? 0x04 : 0x00 ) |
               ( ( c[6] & 1 ) ? 0x02 : 0x00 ) |
               ( ( c[7] & 1 ) ? 0x01 : 0x00 );
    }
    

    This assumes an fixed eight digit binary number. called like this:

    std::cout << to_binary("10101010") << std::endl;
    

    If you had a sixteen bit number you could still use it:

    const char* bin_number = "1010101010101010";
    
    // Deal with 16 bits
    std::cout << ( to_binary( bin_number ) << 8 | to_binary( bin_number + 8 ) ) << std::endl;
    

    Note that there is clearly no bounds checking here and I'm relying on the fact that the LSB of '1' is always 1 and '0' is always 0 (so not validating that it's actually a binary input.)

    Naturally, it's pretty specific and not very flexible, but it does the job and I'm not sure that you'd get much faster.

提交回复
热议问题