Skip to content

Instantly share code, notes, and snippets.

@simonliu009
Last active January 7, 2019 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonliu009/493efd2ffb6a8b4456066b83faaad1d5 to your computer and use it in GitHub Desktop.
Save simonliu009/493efd2ffb6a8b4456066b83faaad1d5 to your computer and use it in GitHub Desktop.
c: int 十进制转二进制输出 dec to bin #c
/*
* @Author: simonliu
* @Date: 2018-04-25 21:48:58
* @Last Modified by: simonliu
* @Last Modified time: 2018-04-25 22:24:15
*/
#define __Mylog__
#ifdef __Mylog__
#define Mylog(format,...) printf("File: " __FILE__ ", Line: %05d: " format "/n", __LINE__, ##__VA_ARGS__)
#else
#define Mylog(format,...)
#endif
#include <stdio.h>
#include "string.h"
void dec2bin(int num);
int main(void)
{ int decimalNum;
printf("Enter number in decimal:");
scanf("%d",&decimalNum);
Mylog("\n Mylog enabled...\n");
Mylog("\n Decimal%d:",decimalNum);
printf("binary format is : \n");
dec2bin(decimalNum);
printf("\n");
return 0;
}
void dec2bin(int num)
{
int i = 0;
int buffer[32];
memset(buffer, 0, sizeof(buffer));
Mylog("\n num= %d, ",num);
if (num < 0)
{
num &= ~(1 << 31); //首位清0,后面按照正数操作
buffer[31] = 1; //首位记录为1
}
Mylog("\n new num= %d, ",num);
while (num >0)
{
if (num&1) //与00000001 按位&, 即检查最后一位是否为1
{
buffer[i] = 1;
Mylog(" buffer[%d] = %d\n",i,buffer[i]);
}
else
{
buffer[i] = 0;
Mylog(" buffer[%d] = %d\n",i,buffer[i]);
}
Mylog("\nnum= %d, ",num);
Mylog("i= %d\n",i);
num = num >> 1 ;
i ++;
}
for (int i = 31; i>=0; i--)
{
printf("%d",buffer[i]);
if (i%4 == 0)
printf(" ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment