简体   繁体   中英

Obtaining a negative value in unsigned int var

Compiling these lines using VS2010

unsigned final_value;
long    int offset=109572;
long    lSize=2;                            //2 Bytes
char    *buffer;
buffer = (char*) malloc (sizeof(char)*lSize);
mybinfile = fopen("binfile.bin","rb");
fseek(mybinfile,offset,SEEK_SET);
fread(buffer,lSize,1,mybinfile);
fclose(mybinfile);
sscanf(buffer,"%u",&final_value);

running this code, final_value returns a negative value. (The same code compiled using NMAKE from console returns correct positive value.) How can I solve this? It can be due to one overflow It can be due to incorrectly setup of my vs2010

thank in advance

scanf is used to read TEXT (strings), you are fetching two bytes and passing that to scanf() - unless your two bytes are precisely two digits (0x30-0x39 in values), and the next byte after that is a zero, it will definitely not do what you expect.

It is not clear exactly what you want your two bytes to represent, but I'm pretty sure what you are doing is "wrong".

As to the value being negative, how are you printing it?

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