#include "stdio.h"
#include "stdlib.h"
void int2binary(int num){
int bi[32];
int k[31] =
{
0x40000000,0x20000000,0x10000000,
0x8000000,0x4000000,0x2000000,
0x1000000,0x800000,0x400000,
0x200000,0x100000,0x80000,
0x40000,0x20000,0x10000,
0x8000,0x4000,0x2000,
0x1000,0x800,0x400,
0x200,0x100,0x80,
0x40,0x20,0x10,
0x8,0x4,0x2,0x1
};
int r, cf = 1;
if(num >= 0) {
bi[0] = 0;
r = num;
}
else {
bi[0] = 1;
r = -1*num;
}
for (int i = 1; i < 32; ++i) {
bi[i] = r/k[i - 1];
r -= k[i - 1]*bi[i];
}
if (bi[0]) {
for (int i = 1; i < 32; ++i) {
if (bi[i] == 0) bi[i] = 1;
else bi[i] = 0;
}
for (int i = 31; i > 0; --i) {
if (cf) {
if (bi[i]) bi[i] = 0;
else {
bi[i] = 1;
cf = 0;
}
}
}
}
for (int i = 0; i < 32; i++) {
printf("%d", bi[i]);
}
printf("\n");
}
int main(int argc, char **argv)
{
int2binary(-500);
return 0;
}
|