Convert decimal to binary and hexadecimal string output using the shift operation

Source: Internet
Author: User
Tags decimal to binary

Function prototype:

 

 
// Convert to binary char * convertto2string (long number); // convert to hexadecimal char * convertto16string (long number );

Ideas:

The binary conversion is simple. You can complete the two-step conversion,

1: The number 1 is shifted to the 31-i (I = {0 31}) position (starting from the high position) in a loop, and then the number is bitwise AND operated,

2: Move the preceding result to the right of 31-i (I = {0, 31}) to see if each bit is 0 or 1,

In this way, the binary bits of each bit are obtained, and then the binary bits are spelled into strings!

 

 

 
Char * convertto2string (long number) {char * output = NULL; Output = (char *) malloc (33); // include '\ 0' int I = 0; (; I <32; I ++) {output [I] = Number & (1 <31-i); Output [I] = output [I]> 31-i; output [I] = (output [I] = 0 )? '0': '1';} output [I] = '\ 0'; return output}

It is a little difficult to convert the hexadecimal format. Consider letters,

 

 

 
Char * convertto16string (long number) {char * output = NULL; char * temp = NULL; Output = (char *) malloc (11); Output [0] = '0 '; output [1] = 'X'; Output [10] = '\ 0'; temp = output + 2; for (INT I = 0; I <8; I ++) {temp [I] = (char) (number <4 * I> 28); // first shift left 4 * I, then right shift 28, every time you process 4 bits of temp [I] = temp [I]> = 0? Temp [I]: temp [I] + 16; // convert to ~ F: Prepare the letter temp [I] = temp [I] <10? Temp [I] + 48: temp [I] + 55; // letter conversion} return output ;}

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.