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 ;}