Implementation and consideration of converting decimal integers to binary

Source: Internet
Author: User
Tags decimal to binary

For decimal to binary conversion, my initial idea is to shift the 32-bit integer to the left one at a time, save the removed one to the corresponding array, finally control the format, and print the output.

Step 1:

Because every time the removed operator is in the highest bit, in order to obtain it, other bits must be shielded. boolean and arithmetic operations are useful, and 32-bit integers are considered, temp = digit & (1 <31) to determine whether the maximum bit is 1 or 0.

If you output it now, an error may occur. For the highest bit 0, this is not a problem, but for the highest bit 1, the binary result may be 1000 0000 0000 0000 0000 0000 0000, translate to decimal is a negative number:-2147483648. this is not what I want, so I shifted 31 places to 0000 again.
0000 0000 0000 0000 0000 0000 00001.

Step 2:

However, I did not expect the right shift operation to be related to the highest bit. For 1000 0000 0000 0000 0000 0000 0000 0000 1111, the 31-bit right shift will become 1111 1111 1111 1111 1111 1111 1111. This is not what I want, so I have to block the result of the right shift again, that is: temp
= (Temp> 31) & 1

Step 3:

As long as the decimal number is not 0, the decimal number is shifted to 1, and digit <= 1 output. The ending condition here is digit! = 0 instead of moving 32 bits to the left, because I used an array and initialized all 32 data to 0. In this way, you do not need to judge all the 0 values on the right of the last 1.

The source code is as follows:

# Include <iostream> using namespace STD; // convert binary void dectobin (INT digit, int bin []) {int I = 0; while (Digit! = 0) {int temp = digit & (1 <31); // judge the highest bit temp = (temp> 31) & 1; // move the highest bit right to the lowest Bit, at the same time, the extended bit is shielded. bin [I ++] = temp; digit <= 1; // The integer is shifted one bit to the left, and the highest bit is automatically discarded and cannot be saved.} int main () {int A =-10002; int B [32] = {0}; cout <"A =" <A <Endl; dectobin (A, B ); cout <"A ="; for (INT I = 0; I <32; I ++) {if (I % 4 = 0) // each four-digit binary {cout <";}cout <B [I] ;}cout <Endl; getchar ();}

The result is returned. However, if you search for it online, there are still better ideas, as shown below:

# Define char_bit 8 void bit_print (int A) {int I; int n = sizeof (INT) * char_bit; int mask = 1 <(n-1 ); for (I = 1; I <= N; ++ I) {putchar (A & Mask) = 0 )? '0': '1'); // this step should be faster. You do not need to move 32-Bit A every time <= 1; if (I % char_bit = 0 & I <n) putchar ('');}}

The above Code does not use arrays, Which is logically better understood and simplifies the judgment in the second step. More importantly, it is cross-platform and can be competent for different machine characters.

In addition, the question of saving the output binary results also raises how to minimize the memory occupied by the output results? So someone implemented it using a string, which is 1/4 of the memory size of my int [] array. The implementation is as follows:

Int dtob (int d, char * BSTR) {If (d <0) Return-1; int mod = 0; char tmpstr [64]; bzero (tmpstr, sizeof (tmpstr); bzero (BSTR, sizeof (BSTR); int I = 0; while (D> 0) {mod = D % 2; D/= 2; tmpstr [I] = mod + '0'; I ++;} unsigned int Len = strlen (tmpstr); for (I = 0; I <Len; I ++) // copy the string {BSTR [I] = tmpstr [len-i-1];} return (INT) Len ;}

However, some people still feel that the above is too arrogant and cannot work when it is a negative number, so there are the following implementations:

void d2b(unsigned int d, char *str){ int nStart = -1, i = 0; for (i=0; i<32; i++) {  bool bOne = (0 != (d & (1 << (32 - i - 1))));  if (bOne && nStart < 0)  {   nStart = i;  }  str[i - nStart] = bOne ? '1' : '0'; } str[i - nStart] = '\0';}

After reading the above implementations, there are still many issues that are not taken into account in the actual programming process, as listed below:

1.What if the input integer is too large? Based on the modularization principle of a function to complete a function, either an error is output, direct return is returned, or dynamic array or linked list is used for processing.

2.Not all input arrays are 0. What should I do? There is a problem with the program I wrote. The only way to avoid this is to initialize it to 0 every time a function is called.

3.If integers are on different machines, their word lengths are different. The second method effectively shields this problem and is worth learning!

4.If the data is too large, another problem occurs. That is, the parameter declares the int type. What if the input parameter is long Int or double? If the data size is too large, excessive digits will be discarded! The solution should be to change the input int parameter to void * pointer, and then perform forced conversion in the function.

5.For a computer, even if an integer such as long double has a limited number of digits, an error will be reported if the number of digits is more than one point! In this way, in addition to the linked list processing in the 1st suggestions, we also need to judge the number of input numbers and block illegal input. The solution is to count the number of input characters, convert the numbers into numeric characters, and then process them accordingly.

In short, for our programmers, the more details they consider, the more robust the code! Flexible minds and hard work are the only way to success.

My program diagram:

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.