如何在C中将无符号整数作为二进制值返回?

时间:2016-01-29 06:45:38

标签: c bit-manipulation bitwise-operators bit 16-bit

更具体地说,我需要创建一个函数float_16(unsigned sign, unsigned exp, unsigned frac),它返回一个bit16表示( bit16是一个typedef无符号整数)给定符号的数字,指数,分数值为无符号整数。

我有以下序言:

int main(int argc, const char * argv[]) {

    typedef unsigned int bit16;
    bit16 a;
    a = 0xABCD; // 1010 1011 1100 1101 in binary = 43981

    printf("Sign is: %d",extractSign(a));
    printf(" ");
    printf("Exponent is: %d",extractExp(a));
    printf(" ");
    printf("Fraction is: %d",extractFrac(a));
    …
}

在我的主程序中,这些值由单独的C文件中的函数检索:

int extractSign(bit16 x) //significant bit
{
    return (x >> 15) & 0x0001; // 0x0001 is mask for 1 bit
}

int extractExp(bit16 x) // 7 bits
{
    return (x >> 8) & 0x007F; // 0x007F is mask for 7 bits
}

int extractFrac(bit16 x) // 8 bit fraction field
{
    return x & 0x00FF; // 0x00FF is mask for 8 bits
}

我如何能够使用这些值来满足此处的要求?

1 个答案:

答案 0 :(得分:0)

您可以使用union

#include <stdio.h>

typedef unsigned short bit16; // On my computer, sizeof (int) == 4, while sizeof (short) == 2

union floating_point
{
    bit16 a;
    struct
    {
        unsigned frac : 8;
        unsigned exp : 7;
        unsigned sign : 1;
    } guts;
};

bit16 float_16 (unsigned sign, unsigned exp, unsigned frac);
unsigned extractSign (bit16 a);
unsigned extractExp (bit16 a);
unsigned extractFrac (bit16 a);

int main(int argc, const char * argv[])
{
    bit16 a = 0xABCD;
    printf("%d\n",a == float_16(extractSign(a),extractExp(a),extractFrac(a)));
    printf("Sign is: %u\n",extractSign(a));
    printf("Exponent is: %u\n",extractExp(a));
    printf("Fraction is: %u\n",extractFrac(a));
    return 0;
}

bit16 float_16 (unsigned sign, unsigned exp, unsigned frac)
{
    union floating_point value;
    value.guts.sign=sign;
    value.guts.exp=exp;
    value.guts.frac=frac;
    return value.a;
}

unsigned extractSign (bit16 a)
{
    union floating_point value;
    value.a=a;
    return value.guts.sign;
}

unsigned extractExp (bit16 a)
{
    union floating_point value;
    value.a=a;
    return value.guts.exp;
}

unsigned extractFrac (bit16 a)
{
    union floating_point value;
    value.a=a;
    return value.guts.frac;
}