C语言实现二进制与十进制转换

本文介绍了一个简单的C++程序,该程序能够将十进制整数转换为二进制表示,并对其进行反转操作。此外,还展示了如何将反转后的二进制字符串再转换回十进制数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*************************************************************************
    > File Name: test.cpp
    > Author: Damon
    > Mail: thydamon@gmail.com 
    > Created Time: Fri 05 Jun 2015 02:28:03 AM PDT
 ************************************************************************/

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

void rever(char *pIn, char *pOut)
{
	char *pTin  = pIn;
	char *pTout = pOut;
	int i = 0, j = 0;

	while (pTin[i] != '*')
	{
		i++;
	}
	
	while (i--)
	{
		pOut[j] = pIn[i];
		j++;
	}
	pOut[j] = '*';	
}

void putArr(char *nIn)
{
	int i = 0;
	
	while (nIn[i] != '*')
	{
		printf("%c ", nIn[i]);
		i++;
	}
	printf("\n");
}

void TentoTw(const int nIn, char *nOut)
{
	int  nTmp  = nIn;
	char *pTmp = nOut;
	int  i = 0;

	while (nTmp)
	{
		// printf("%d ", nTmp/2);
		pTmp[i] = nTmp%2 + 48;
		// printf("%d\n", *pTmp);
		// pTmp++;
		i++;
		nTmp = nTmp/2;
	}

	pTmp[i] = '*';
}

void TwtoTen(char *pIn)
{
	char *pTin = pIn;
	int  i = 0, num = 0, j = 0;
	
	while (pTin[j] != '*')
		j++;
	//printf("%d\n",j);
	while (pTin[i] != '*')
	{
		printf("%c ",pTin[i]);
		num = num+(pTin[i] - 48)*pow(2,j-i-1);
		i++;
	}
	printf("\n");
	printf("%d\n",num);
}

int main(int argc, char* argv[])
{
	int  in = 0;
	char str[32] = {0};
	char fstr[32] = {0};

	printf("please input a integer:");
	scanf("%d", &in);
	TentoTw(in, str);
	putArr(str);
	rever(str,fstr);
	putArr(fstr);
	TwtoTen(fstr);

	return 0;
}


g++ test.cpp -o test -lm 编译即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值