简体   繁体   中英

How can I return an unsigned integer as a binary value in C?

More specifically, I need to make a function float_16(unsigned sign, unsigned exp, unsigned frac) , that returns a bit16 representation ( bit16 is a typedef unsigned integer ) of a number given a sign, exponent, and fraction values as unsigned integers.

I have the following preamble:

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));
    …
}

In my main program, and these values are retrieved by the functions in a separate C file:

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
}

How would I be able to use these values to fulfill what is being asked here?

You can use an 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM