C Primer Plus 第六版 第十五章 编程练习

1.编写一个函数,把二进制字符串转换为一个数值。例如,有下面的语句:

char * pbin = "01001001";

那么把pbin作为参数传递给该函数后,它应该返回一个int类型的值73。

#include <stdio.h>
#include <string.h>
#define SIZE 9
char * s_gets(char * st,int n);
struct bin{
	unsigned int eight: 1;
	unsigned int seven: 1;
	unsigned int six:   1;
	unsigned int five:  1;
	unsigned int four:  1;
	unsigned int three: 1;
	unsigned int two:   1;
	unsigned int one:   1;
};
int str_bin(char * pbin)
{
	struct bin abin;
	int i;

	abin.eight=*pbin-48;
	abin.seven=*(pbin+1)-48;
	abin.six=*(pbin+2)-48;
	abin.five=*(pbin+3)-48;
	abin.four=*(pbin+4)-48;
	abin.three=*(pbin+5)-48;
	abin.two=*(pbin+6)-48;
	abin.one=*(pbin+7)-48;
	i=abin.eight*128+abin.seven*64+abin.six*32+abin.five*16+abin.four*8+abin.three*4+abin.two*2+abin.one*1;

	return i;
}
//测试函数
int main(void)
{
	char binstr[SIZE];

	printf("Enter a binstr,then convert to integer(new line to terminate):\n");
	while(s_gets(binstr,SIZE)&&binstr[0]!='\0')
	{
		printf("The value of binstr is :%d\n",str_bin(binstr));
		printf("Enter next binstr,and then convert it(new line to terminate):\n");
	}
	printf("Done.\n");

	return 0;
}

char * s_gets(char * st,int n)
{
	char * ret_val;
	char * find;

	ret_val=fgets(st,n,stdin);
	if(ret_val)
	{
		find=strchr(st,'\n');
		if(find)
			*find='\0';
		else
			while(getchar()!='\n')
				continue;
	}

	return ret_val;
}

2.编写一个程序,通过命令行参数读取两个二进制字符串,对这两个二进制数使用~运算符、& 运算符、| 运算符和^ 运算符,并以二进制字符串形式打印结果(如果无法使用命令行环境,可以 通过交互式让程序读取字符串)。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int str_int(char * str);           // 字符串转换为整数函数
char * itobs(int n,char * ps);     // 整数转换为二进制函数
int main(int argc,char * argv[])
{
	int i,j;
	char ps[CHAR_BIT*sizeof(int)];   // 整数所占位数

	if(argc<3)
	{
		puts("Need at least 3 argvments.");
		exit(EXIT_FAILURE);
	}
	i=str_int(argv[1]);
	j=str_int(argv[2]);
	printf("i:%s\n",itobs(i,ps));
	printf("~%s is %s\n",argv[1],itobs(~i,ps));     // 非运算
	printf("~%s is %s\n",argv[2],itobs(~j,ps));     // 非运算
	printf("%s & %s is %s\n",argv[1],argv[2],itobs(i&j,ps));     // 与运算
	printf("%s | %s is %s\n",argv[1],argv[2],itobs(i|j,ps));     // 或运算
	printf("%s ^ %s is %s\n",argv[1],argv[2],itobs(i^j,ps));     // 异或运算

	return 0;
}
int str_int(char * pbin)
{
	int bin=0;
	int e=1;
	int i;

	for(i=strlen(pbin)-1;i>=0;i--)
	{
		bin+=(*(pbin+i)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值