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


more specifically, need make function float_16(unsigned sign, unsigned exp, unsigned frac), returns bit16 representation (bit16 typedef unsigned integer) of number given sign, exponent, , fraction values unsigned integers.

i have following preamble:

int main(int argc, const char * argv[]) {      typedef unsigned int bit16;     bit16 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 main program, , these values retrieved functions in separate c file:

int extractsign(bit16 x) //significant bit {     return (x >> 15) & 0x0001; // 0x0001 mask 1 bit }  int extractexp(bit16 x) // 7 bits {     return (x >> 8) & 0x007f; // 0x007f mask 7 bits }  int extractfrac(bit16 x) // 8 bit fraction field {     return x & 0x00ff; // 0x00ff mask 8 bits } 

how able use these values fulfill being asked here?

you can use union.

#include <stdio.h>  typedef unsigned short bit16; // on 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 = 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; } 

Comments