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

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

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

我有以下序言:

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
}

我怎样才能使用这些值来满足这里的要求?

最佳答案

您可以使用 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;
}

关于c - 如何在 C 中将无符号整数作为二进制值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078453/

相关文章:

C使用malloc和复制数组

c++ - Code::Block 未创建调试版本?

c - 在没有 fork() 的情况下获取 fork()ing 的写时复制行为

c - 按位操作 : After a series of consecutive bits, 将最左边的不同位传播到右边

Python 就地补码运算符

C共享内存双 vector

java - 如何比 Newton Raphson 更有效地计算 Big Decimal 的平方根?

swift - 如何在 Swift 中使用位操作?

swift - Bit shift OptionSet 是 7 的倍数? swift 3

c++ - | 有什么用(按位或运算符)在 setiosflags 的上下文中?