4

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.

0

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

5 Comments

gcc warns about this if you provide -Wuninitialized, which is included in -Wall
I warned the OP without any options. ;-)
yup you are right!! thanks!! is it because tested gets initialized with garbage and all i'm doing is overwriting on that?
Yes. A word of warning however. You probably want to make the array an array of unsigned char or you'll be bit by a sign bit if your compiler treats plain char as signed. (Pun intended)
i know. but in my main application i am not really in control of the buffer, it's going to be passed to me. thanks for the warning :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.