|
-
September 4th, 2012, 09:17 PM
#1
Streaming Bytes into an Integar
Hello,
I have a FILE stream, and I want to create a function that streams a specified number of bytes (up to four bytes) and returns the value of this, as an integar.
For example, supposing that my FILE has the following data, in hex: 74 C8 02 33 F2 7B....... I then want to stream three bytes and store this as an integar. So, I want to stream "04 08 02". The data stored in the integar should then be "00 74 C8 02", because I have not streamed anything into the first byte. By converting the hex to dec, the integar should then be of the value 7653378 (if it is unsigned).
To try to achieve this, I have written the following function. I create an integar and initialise it to zero, then take each byte from the stream, and OR it with my integar. Then, I shift the integar left by 8, and read the next byte, and so on.
The problem is, when I convert "c" to "c_int", it adds on a load of 1's to the left of the "c" data. This then means that the OR comparison changes all those bits in my integar to 1.
Any ideas on how to solve this? I am also wondering whether there is a much more simple way of doing this, rather than having to write my own function....
Thanks!
Code:
int StreamFileToInt(FILE *fp, int num_bytes)
{
char c;
int c_int;
int x = 0x0000;
for (int i = 0; i < num_bytes; i++)
{
c = getc(fp);
c_int = (int)c;
x = x | c_int;
x << 8;
}
return x;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|