位操作之按位视图,该如何解决
位操作之按位视图
我编了一个程序,以下是程序的开头部分。我的意思是用unsigned long来保存一个字体信息,用按位视图方法。
从左往右依次是1位(U),1位(I),1位(B),2位(ALIGNMENT),1位(空位), 7位(SIZE 0-172),8位(ID 0-255)
我初始化了font,想让它一开始显示ID,SIZE,ALIGNMENT,B,I,U依次为1,12,left,off,off,off
而问题就出在程序显示的是1,12,left,on,on,on
请问这是咋回事儿呢?
#include <stdio.h>
int main (void)
{
unsigned long i;
char ch;
unsigned long font = 0x010c01;
while (1)
{
puts ("ID SIZE ALIGNMENT B I U");
printf ("%lu %lu ", font & 0xff, (font >> 8) & 0x7f);
switch ((font >> 16) & 3)
{
case 1: printf ("left ");break;
case 2: printf ("center ");break;
case 3: printf ("right ");break;
default: printf ("wrong input");break;
}
if ((font >> 18) & 1 == 0)
printf ("off ");
else
printf ("on ");
if ((font >> 19) & 1 == 0)
printf ("off ");
else
printf ("on ");
if ((font >> 20) & 1 == 0)
printf ("off\n");
else
printf ("on\n");
}
return 0;
}
------解决方案--------------------
像这个测试位的操作这样写更好些
我编了一个程序,以下是程序的开头部分。我的意思是用unsigned long来保存一个字体信息,用按位视图方法。
从左往右依次是1位(U),1位(I),1位(B),2位(ALIGNMENT),1位(空位), 7位(SIZE 0-172),8位(ID 0-255)
我初始化了font,想让它一开始显示ID,SIZE,ALIGNMENT,B,I,U依次为1,12,left,off,off,off
而问题就出在程序显示的是1,12,left,on,on,on
请问这是咋回事儿呢?
#include <stdio.h>
int main (void)
{
unsigned long i;
char ch;
unsigned long font = 0x010c01;
while (1)
{
puts ("ID SIZE ALIGNMENT B I U");
printf ("%lu %lu ", font & 0xff, (font >> 8) & 0x7f);
switch ((font >> 16) & 3)
{
case 1: printf ("left ");break;
case 2: printf ("center ");break;
case 3: printf ("right ");break;
default: printf ("wrong input");break;
}
if ((font >> 18) & 1 == 0)
printf ("off ");
else
printf ("on ");
if ((font >> 19) & 1 == 0)
printf ("off ");
else
printf ("on ");
if ((font >> 20) & 1 == 0)
printf ("off\n");
else
printf ("on\n");
}
return 0;
}
------解决方案--------------------
像这个测试位的操作这样写更好些
- C/C++ code
if (font & (1L<<18)) printf ("on "); else printf ("off ");