Convert decimal to binary string

Source: Internet
Author: User
Tags decimal to binary

To complete a CRC (Cyclic Redundancy checksum) coding task assigned by the instructor today, a subroutine is to be converted from decimal to binary string for display! Don't do it, don't know ~~~ It turned out that I had no temper after debugging ~~!! I can't think of it as simple as I thought it was actually a lot of things to consider ~~~ Almost got hit ~~~ (For convenience, use the cstring class in MFC)

 

// Convert decimal to binary
Void CCRC: dectobinary (cstring & changestring)
{

// Convert the number of string type to a long integer.
Unsigned long num = atol (changestring. getbuffer (changestring. getlength ()));
Unsigned long temp = 1;

Int K = 0;

// Obtain the power no greater than the current number, and set the string length.
While (temp <num)
{
K ++;
Temp * = 2;
}

// Reset the string length

Changestring. getbuffersetlength (k );
Changestring. setat (0, '1 ');

Temp/= 2;
Num-= temp;
 
K = 1;

// When the number of conversions is greater than 0, find a two-power number not greater than num,
While (Num> = 0 & temp! = 0)
{
Temp/= 2; // This sentence is very important
While (Num <temp)
{

// If temp is smaller than num, set it to 0.
Changestring. setat (K ++, '0 ');
Temp/= 2;
}

// This condition is used to process the last bit.
If (num! = 0)
Changestring. setat (K ++, '1 ');
Num-= temp;
 
}

}

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.