/*------------------------------------
invert4.c -- 使用位操作显示二进制
------------------------------------*/ #include <stdio.h>
#include <limits.h> //提供 CHAR_BIT 的定义,CHAR_BIT 表示每字节的位数 char* itobs(int, char*);
void show_bstr(const char*);
int invert_end(int num, int bits); int main()
{
char bin_str[CHAR_BIT * sizeof(int) + ];
int number; puts("Enter integers and see them in binary.");
puts("Non-numeric input terminates program"); while (scanf("%d", &number) == )
{
itobs(number, bin_str); printf("%d is ", number); show_bstr(bin_str); putchar('\n'); number = invert_end(number, ); printf("Inverting the last 4 bits gives\n"); show_bstr(itobs(number, bin_str)); putchar('\n');
} puts("Bye"); return ;
} char* itobs(int n, char *ps)
{
const static int size = CHAR_BIT * sizeof(int); for (int i(size - ); i >= ; --i, n >>= )
ps[i] = ( & n) + ''; ps[size] = '\0'; return ps;
} //以4位为一组,显示二进制字符串
void show_bstr(const char *str)
{
int i = ;
while (str[i]) //不是空字符
{
fputc(str[i], stdout); if (++i % == && str[i])
fputc(' ', stdout);
}
} int invert_end(int num, int bits)
{
int mask = ;
int bitval = ; while (bits-- > )
{
mask |= bitval;
bitval <<= ;
} return num ^ mask;
}

invert4.c

第 15 章 位操作(invert4)-LMLPHP

05-08 08:37