-
unwanted sign extension
i am trying to read from a binary file.
hexcode of the binary:
ff d8 ff d2 44 54 39 02 23 03 05
Code:
char buf[20];
fread(buffer,sizeof(char),4,in);
buf[0]=buf[0]&0xff;
buf[1]=buf[1]&0xff;
printf(" %x %x",buf[0],buf[1]);
half the times i get this as teh out put:
ff d8
rest of teh times :
ffffffff ffffffd8
compiler i am using is dmc;
i want the output to be consistently ff d8 all of the times.what do i need to do for that?
-
-
ok thats one way to do it.HIGHLY COMMENDABLE.
what if i dont know what the first two bits r and still want the output to be consistent?**
(**dont tell me i need to try out multiple times and then finally when i do have an idea of what the first 2 bits r i use printf( firstbit,secondbit) for consistency.)
-
try something along these lines:
Code:
char buf[20];
fread(buffer,sizeof(char),4,in);
int num1=buf[0]&0xff;
int num2=buf[1]&0xff;
printf(" %x %x",num1,num2);
%x makes printf expect an int but you send a char....so you sent 3 bytes less than expected.
Some speculations: because printf wants an int but gets a char, it will access some memory that hasnt been initiallized or is even used by you.
-
i think that should help.
thank you.
-
Declare buf[] as unsigned char instead?