A good conversion method between binary and decimal

Source: Internet
Author: User

If I want to give you a binary 1101101010101, I will ask you how much it is to convert it into a 10-digit system. The first thing I think of is to use the k power of 2.

In fact, we don't need to use the following code at all. ------- we assume that we accept this binary string. we generally do the same.

1 for( int i = 0 ; str[i]!=‘\0‘ ; i++ )2 {3     sum = sum*2 + str[i] - ‘0‘;4 }

We achieved K power through this * 2 because I = 0 is exactly the highest bit in binary.

 

Similarly, if I want to give you a decimal number of 23421, what is the quick way to convert it into a binary number?

We use Val to represent this decimal number and store the converted binary sequence in the STR string array.

 1     while(n) 2     { 3         str[cnt++] = (n&1)+‘0‘; 4                 // str[cnt++] = n%2+‘0‘; 5         n >>=1; 6     } 7     for( int i = cnt-1 ; i>=0 ; i-- ) 8     { 9         cout << str[i];10     }

There can be two ways to write N & 1 and N % 2. The speed of writing the former is faster, but do not forget the brackets according to the operator priority.

Also, the output order is backward. Do not make a mistake =-=.

I think this may be useful in the game.

 

Today:

Like is arrogant, but love is restrained

I have not read this sentence yet

What does this love mean?

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.