tiger0516
asked on
DEC,HEX conversion
Hi folks,
I have a question:
I am reading a binary file. If I use printf with %d, I will see the output as -1 -1 -1 59; if with %x, then ff ff ff 3b. The problem is that, -1 -1 -1 59 actually represents a value of -197. How can I get -197 from -1 -1 -1 59? Thanks
Thanks
(I use fread to read bytes from the file)
Urgent :-)
I have a question:
I am reading a binary file. If I use printf with %d, I will see the output as -1 -1 -1 59; if with %x, then ff ff ff 3b. The problem is that, -1 -1 -1 59 actually represents a value of -197. How can I get -197 from -1 -1 -1 59? Thanks
Thanks
(I use fread to read bytes from the file)
Urgent :-)
ASKER
Kent,
Many thanks! I think it should work. But there is an error whem compiling:
(using gcc )
Error part2.c 52: Call of non-function in function main
(line 52) iValue = (uBuffer[0] << 24) | (uBuffer[1] << 16) | (uBuffer[2] < 8) (uBuffer[3]);
Thank you.
Many thanks! I think it should work. But there is an error whem compiling:
(using gcc )
Error part2.c 52: Call of non-function in function main
(line 52) iValue = (uBuffer[0] << 24) | (uBuffer[1] << 16) | (uBuffer[2] < 8) (uBuffer[3]);
Thank you.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi Sunny,
What can I say? In this time zone we're all tired and ready for bed. :~}
Kent
What can I say? In this time zone we're all tired and ready for bed. :~}
Kent
It appears that you've read the individual bytes and need to pack them into an integer word. This goes a lot smoother if you'll read them into an unsigned char buffer or cast a pointer to the buffer as unsigned. C wants to sign extend and that sometimes gets messy. Since this example has all 1 bits in the upper three bytes it's not critical, but as soon as any of those bits becomes a 0 sign extension is a problem.
Here's a bit of code that should help.
char Buffer[4];
unsigned char *uBuffer;
int iValue;
fread (Buffer, 1, 4, Stream);
uBuffer = (unsigned char*) Buffer;
// If the system is big endian
iValue = (uBuffer[0] << 24) | (uBuffer[1] << 16) | (uBuffer[2] < 8) (uBuffer[3]);
// I f the system is little endian
iValue = (uBuffer[3] << 24) | (uBuffer[2] << 16) | (uBuffer[1] < 8) (uBuffer[0]);
Good Luck!
Kent