c语言 >> 问题
我以为的>>3后 左侧会补0,但是我的程序为什么会补1啊
//将char转成10100010这样的字符串 只取bit位从左侧数前n位
char* print_b(unsigned char c, int n)
{
int i = 0;
char* res;
res = (char*)malloc(n + 1);
memset(res, '\0', n + 1);
unsigned char tmp = 0;
for (i = 0; i < n; i++)
{
//c=00001001
//就是为了要把某一位给摘出来
tmp = c >> (7 - i);//c=00000001
tmp = tmp << 7;//c=10000000
if (tmp > 0)
res[i] = '1';
//strcat(res, "1");
else
res[i] = '0';
//strcat(res, "0");
}
return res;
}
int main()
{
char p = 0b10100011;
printf("%s\n", print_b(p,8));
printf("%s\n", print_b( p>>3,8));
return 9;
}
程序打印结果为
10100011
11110100
环境centos 64位
gcc环境
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)