位操作转换二进制
位操作转换转换二进制
可以用递归的方法将数字转换为二进制数据,也可以用C
语言中的移位运算符来解决。
/** @Author: WangYunLong* @Date: 2020-03-03 20:35:54* @Last Modified by: WangYunLong* @Last Modified time: 2020-03-03 21:13:20*/
#include <stdio.h>
#include<stdlib.h>
#include<limits.h>
char *itobs(int n,char *ps);
void show_bstr(const char *string);
int main()
{char bin_str[CHAR_BIT*sizeof(int) +1];int number;puts("Enter integers and see them in binary");puts("Non-numeric input terminates program.");while (scanf("%d",&number)==1){itobs(number,bin_str);show_bstr(bin_str);puts("\n");}puts("Bye!");getchar();getchar();return 0;
}
char *itobs(int n,char *ps)
{const static int SIZE = CHAR_BIT*sizeof(int);for(int i = SIZE-1;i>=0;i--,n>>=1){ps[i]=(01 & n)+'0';}ps[SIZE] = '\0';return ps;
}
void show_bstr(const char *string)
{int i = 0;while (string[i]){putchar(string[i]);if(++i % 4 == 0 && string[i]){putchar(' ');}}
}
limits.h
文件中提供CHART_BIT
宏,表示字节的位数bin_str
数组的元素个数是CHAR_BIT*sizeof(int) +1
,剩下一个元素留给空字符。itobs()
函数返回的地址与传入的地址相同
在每执行一次
for()
循环中,对01 & n
求值,01是八进制形式的掩码,该作用是取出n
的最后一位,但对于
char
类型的数组而言,要加上基础值'0'
对应的ASCII
码,即可完成这种转换,将其结果放在倒数第二位上(最后一位放字符
'0'
).
顺带一提,01 & n或者1 & n都行。
位操作转换二进制
位操作转换转换二进制
可以用递归的方法将数字转换为二进制数据,也可以用C
语言中的移位运算符来解决。
/** @Author: WangYunLong* @Date: 2020-03-03 20:35:54* @Last Modified by: WangYunLong* @Last Modified time: 2020-03-03 21:13:20*/
#include <stdio.h>
#include<stdlib.h>
#include<limits.h>
char *itobs(int n,char *ps);
void show_bstr(const char *string);
int main()
{char bin_str[CHAR_BIT*sizeof(int) +1];int number;puts("Enter integers and see them in binary");puts("Non-numeric input terminates program.");while (scanf("%d",&number)==1){itobs(number,bin_str);show_bstr(bin_str);puts("\n");}puts("Bye!");getchar();getchar();return 0;
}
char *itobs(int n,char *ps)
{const static int SIZE = CHAR_BIT*sizeof(int);for(int i = SIZE-1;i>=0;i--,n>>=1){ps[i]=(01 & n)+'0';}ps[SIZE] = '\0';return ps;
}
void show_bstr(const char *string)
{int i = 0;while (string[i]){putchar(string[i]);if(++i % 4 == 0 && string[i]){putchar(' ');}}
}
limits.h
文件中提供CHART_BIT
宏,表示字节的位数bin_str
数组的元素个数是CHAR_BIT*sizeof(int) +1
,剩下一个元素留给空字符。itobs()
函数返回的地址与传入的地址相同
在每执行一次
for()
循环中,对01 & n
求值,01是八进制形式的掩码,该作用是取出n
的最后一位,但对于
char
类型的数组而言,要加上基础值'0'
对应的ASCII
码,即可完成这种转换,将其结果放在倒数第二位上(最后一位放字符
'0'
).
顺带一提,01 & n或者1 & n都行。
发布评论