首页
登录 | 注册

C程序习题-取出二进制数的奇位数[12.2]

    写一个函数,对一个16位的二进制数取出它的奇位数(即从左边起第1,3,5,7...15位)。
    代码如下:

#include <stdio.h>

unsigned short getbits(unsigned short value);
int main(int argc,char *argv[])
{
    unsigned short int a;
    printf("input an octal number:");
    scanf("%o",&a);
    printf("result:%o\n",getbits(a));
    system("pause");
    return 0;
}

unsigned short getbits(unsigned short value)
{
    int i,j;
    unsigned short int z,a,q;
    z = 0;
    for (i = 1; i <= 15; i+=2)
    {
        q = 1;
        for (j = 1; j <= (16 - i - 1)/2; j++)
        {
            q *= 2;
        }
        a = value >> (16 - i);
        a <<= 15;
        a = a > 15;
        z += a * q;
    }
    return z;
}



相关文章


2020 unjeep.com webmaster#unjeep.com
12 q. 0.014 s.
京ICP备10005923号