Search code examples
c++cbit-manipulationmemcpy

how to put an unsigned int into a char array and extract it back


can someone explain why this isn't working? i am trying to put an unsigned int into a char buffer and then fetch it back into another unsigned int.

  1 #include<stdio.h>
  2 #include<string.h>
  3 int main(){
  4   unsigned int tester = 320;
  5   char buffer[512];
  6   memset(buffer,0,512);
  7   memcpy(buffer,&tester,sizeof(unsigned int));
  8   /*buffer[0]|=tester;
  9   buffer[1]|=(tester>>8);
 10   buffer[2]|=(tester>>16);
 11   buffer[3]|=(tester>>24);*/
 12   unsigned int tested;
 13   memcpy(&tested,buffer,sizeof(unsigned int));
 14 
 15   /*tested|=(buffer[3]<<24);
 16   tested|=(buffer[2]<<16);
 17   tested|=(buffer[1]<<8);
 18   tested|=(buffer[0]);*/
 19   printf("\n %d\n",tested);
 20 }

when i do memcpy it works. but when i take the bitwise approach it doesn't work. funny thing is when i put buffer size as 20 it works. but when i use large buffers, or even 50, it always prints 368 in the bitwise appraoch. again the memcpy works fine.


Solution

  • When you declare test on line 12 unsigned int tested; it should be initialized to zero unsigned int tested =0; Also, compiling with -Wuninitialized or -Wall would have warned you tested was uninitialized.