bit manipulation - How do I convert an int into 5-bit 2s complement in C? -


i have -9 integer, how convert 5 bit 2s complement integer in c? getting 10111?

what current code looks like:

char src2[3] = "-9"; int int_src2 = atoi(src2); int_src2 = int_src2 & 31; 

my immediate thoughts int_src2 8388112 when set 16 after , operation - whereas wanted 10111

you use combination of bitfields , unions:

#include <stdio.h>  typedef struct {     unsigned int bit1:1;     unsigned int bit2:1;     unsigned int bit3:1;     unsigned int bit4:1;     unsigned int bit5:1; } five;  typedef union {five f; int i;} u;  int main() {     u test;     test.i = -9;     printf("%u%u%u%u%u\n",test.f.bit5,test.f.bit4,test.f.bit3,test.f.bit2,test.f.bit1);     return 0; } 

live example: https://ideone.com/ow0bl6


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -