Fast way to convert a binary number to a decimal number

前端 未结 5 1714
感情败类
感情败类 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:16

    Well, if this "number" is actually a string gotten from some source (read from a file or from a user) that you converted into a number (thinking it to be more appropriate for an actual number), which is quite likely, you can use a std::bitset to do the conversion:

    #include 
    
    unsigned int number = std::bitset<32>("10101010").to_ulong();
    

    (Of course the 32 here is implementation-defined and might be more appropriately written as std::numeric_limits::digits.)

    But if it is really a number (integer variable) in the (very) first place you could do:

    #include 
    
    unsigned int number = std::bitset<32>(std::to_string(bin_number)).to_ulong();
    

    (using C++11's to_string) But this will probably not be the most efficient way anymore, as others have presented more efficient algorithms based on numbers. But as said, I doubt that you really get this number as an actual integer variable in the very first place, but rather read it from some text file or from the user.

提交回复
热议问题