C语言 int类型转换成二进制

使int n依次和2的次方进行与操作(&),得知每个位是0还是1,并且写入字符数组,返回写有数字二进制信息的字符指针。

#include <stdio.h>
#include <stdlib.h>

char *toBinary(int num)
{
    char *binary = (char *)malloc(sizeof(char) * 33);
    int flag = 1;
    int i;

    for (i = 31; i >= 0; i--)
    {
        if (num & flag)
        {
            binary[i] = '1';
        }
        else
        {
            binary[i] = '0';
        }
        flag<<=1;
    }
    binary[32] = '';

    return binary;
}

int main()
{
    char *tmp;
    for (int i = -16; i <= 16; i++)
    {
        tmp = toBinary(i);
        printf("%d:	%s
", i, tmp);
        free(tmp);
        tmp = NULL;
    }

    return 0;
}
#include<stdio.h>
#include<stdlib.h>

char* ToBin(int num)
{
	int flag=1;
	char* result=(char*)malloc(sizeof(char)*33);
	int i;

	for(int i=31;i>=0;i--)
	{
		if(num & flag)
		{
			result[i]='1';
		}
		else
		{
			result[i]='0';
		}
		flag<<=1;
	}
	result[32]='';
	return result;
}

int main()
{
	int a1=28;
	int a2=-28;
	char* a;
	int i=0;
	printf("%s","I am CDQ!
");
	a = ToBin(a1);
       //a= ToBin(a2);
	printf("a1:");
	for(int i=0;i<33;i++)
	{
		printf("%c",a[i]);
	}
	printf("%c",'
');
	free(a);
	a = NULL;

	return 0;
}
I am CDQ!
a1:00000000000000000000000000011100
I am CDQ!
a2:11111111111111111111111111100100

参考链接:
https://www.cnblogs.com/noonjuan/p/12343042.html

原文地址:https://www.cnblogs.com/chendeqiang/p/14224853.html