C语言 十进制转二进制,并保存在数组中

#include <stdio.h>
#define uint unsigned int
#define ushort unsigned short

uint transform_data(uint frequence,ushort* pwm_table)
{
	uint temp = frequence;
	int pwm_index = 0;
	
	while(temp)
	{
		pwm_table[pwm_index] = (temp&0x01);
		temp = temp>>1;
		pwm_index++;
	}
	return pwm_index;	
}
int main(){
	uint frequence = 2;
	//scanf("%d",&frequence);		
	ushort pwm_table[15] = {0};
	uint off_set;
	
	off_set = transform_data(frequence,pwm_table);
	
	int i=0;
	for(i=off_set-1;i>=0;i--)
	{
		printf("%d",pwm_table[i]);
	}			
	return 0;
}
//输出结果:10

以前写的时候,总是想着要对2取余,再除2,今天看到别人写的程序,才想起来,直接取他的最低位,然后右移就是除2。(~o ̄3 ̄)~

 

》————————————————————————————————————————————————《

上次写的只能转换正数,现在又把负数加上去了,感觉程序写的太繁琐了,有没有更简单的方法。

#include <stdio.h>
#define uint unsigned int
#define ushort unsigned short
//求2的N次方  
int cifang(int n)
{
	int i = 0,sum = 1;
	for(i = n;i>0;i--)
	{
		sum *= 2;
	}
	return sum;
}
//十进制正数转换成二进制数 
uint transform_data_zhengshu(uint frequence,ushort* pwm_table)
{
	uint temp = frequence;
	int pwm_index = 0;
	
	while(temp)
	{
		pwm_table[pwm_index] = (temp&0x01);
		temp = temp>>1;
		pwm_index++;
	}
	return pwm_index-1;	
}

uint transform_data(int frequence,ushort* pwm_table)
{
	int temp = frequence;
	int pwm_index = 0;
	ushort pwm_temp[15]={0};
	//负数	
	if(frequence<0) 
	{
		//先将负数转换成正数 
		temp = -frequence;
		
		//求出这个正数temp的二进制并存放在pwm_temp中	
		transform_data_zhengshu(temp,pwm_temp);
		
		//将这个正数temp的二进制pwm_temp取反并转换成十进制数 sum 
		int sum = 0;
		int i = 0;
		for(i = 0;i < 15;i++)
		{
			if(pwm_temp[i]==0)
				pwm_temp[i]=1;
			else
				pwm_temp[i]=0;
		
			sum += cifang(i)*pwm_temp[i];			
			pwm_temp[i] = 0;
		}
		
		//将转换出来的十进制数sum加一 
		sum += 1;
		//printf("sum=%d\n",sum);
		
		//最后再转成二进制pwm_table
		return transform_data_zhengshu(sum,pwm_table);		
	}
	
	//正数 
	return transform_data_zhengshu(frequence,pwm_table);					
}

int main(){
	int frequence = -2;
	//scanf("%d",&frequence);	
	ushort pwm_table[15] = {0};
	uint off_set;
	
	off_set = transform_data(frequence,pwm_table);
	
	int i=0;
	for(i=off_set;i>=0;i--)
	{
		printf("%d",pwm_table[i]);
	}
	return 0;
}

 

    原文作者:进制转换
    原文地址: https://blog.csdn.net/HK_JY/article/details/81288172
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞