Purpose: Converts a decimal number x to a binary number and prints it out.
Main idea: On my machine, a short variable occupies two bytes, a continuous 16-bit, first define a short variable i, and then divide it into two eight-bit parts (s, (s+1)), with the pointer operation of the two parts, the high address of the eight-bit assignment is 0, the low address of the eight-bit assignment x, Thus, the number to be converted is stored in binary form in the eight bits pointed to by S. Then I move the I to the left one bit, then the highest bit in the binary of X will enter the s+1 binary lowest bit, at this time, get s+1 point to the value. A bits of x is obtained, and then the s+1 point is zeroed, and this operation is repeated to get all the bits.
The following is the code: (also made a gray code conversion, x eight bit size, because the computer stores negative numbers in complementary form, so negative numbers will show complement)
#include <stdio.h>
int xor (int, int);
int main ()
{
int t=0;
int tem;
short I; I occupy 16-bit
char *s=&i; S gets the first address of I because of char type, which accounts for eight-bit
int result[8]; Store binary result
int graycode[8];
* (s+1) =0; High eight-bit assignment 0
printf ("--decimal:");
scanf ("%d", &tem);
*s=tem;
for (t=0;t<8;t++)
{
i=i<<1; Gets a value
result[t]= (int) * (s+1) by shifting;
* (s+1) =0; Re-assign the value 0
}
t=0;
printf ("Bin Code:");
for (t=0;t<8;t++)
printf ("%d", result[t]);
Graycode[0]=xor (0,result[0]);
printf ("\ngray code:%d", graycode[0]);
for (t=1;t<8;t++)
{
graycode[t]=xor (result[t-1],result[t]);
printf ("%d", graycode[t]);
}
printf ("\ n");
return 0;
}
int xor (int x,int y)
{
if (x==y)
return 0;
else
return 1;
}
As for the variable bit in memory storage, from the high address to the low address or other, temporarily still consult the data, in order to be sure.