How to copy 2 bytes from a file an put into result variable?

AI Thread Summary
The discussion focuses on reading two data files containing 10-bit data represented by 16-bit words in C++. The user successfully opens the files in binary mode but struggles with combining two bytes into a single value for calculations. The solution involves reading the two bytes into an unsigned short variable and using bitwise operations to separate the high and low bytes. The final value is computed by multiplying the high byte by 256 and adding the low byte. The user expresses gratitude for the guidance and plans to implement the solution.
Leannie
Messages
7
Reaction score
0
Hi! I don't know if I am even wording this right but here goes. I have to write a programme to read two data files into C++, then ouput as one file in the same format.

The two files are files of 10 bit data. Each 10-bit recorded value is represented by a 16 bit word, of which the top 6 bits are not in use.

I have managed to read in the files using "ifstream inFile(. . . . .)"

I want to ouput the result as ((data1-data2)/(data1+data2))*1000.

I have tried using "inFile.get()" but that only takes 1 byte from the file and puts it into my result variable. Hence I end up with every value as 00. I want to take the first byte and times by 256 (100 in hexidecimal) and add the 2nd byte on.

My problem is how do I copy 2 bytes of data?

I know it is something to do with byte swapping, lobyte and high byte and I want C=A*256+B where every A is 00. But I have no idea how to do this?

Any help would be great,
thanks in advance :)
 
Physics news on Phys.org
When you use the ifstream constructor, in what mode are you opening the file? It seems to me you should be opening it in binary mode, not in text mode.
 
Hi! I am opening it in binary format as below, I do the same with both files so do this twice.

ifstream inFile1("h:\\data1.dat",ios::in,ios::binary);

I don't know how write code to multiply the first byte by 256 and add on the second byte though. I want to place this new value in my result variable so that I can output my results as required.

Thanks
 
You need to read two bytes from the file, and then separate these into high and low bytes.

Let's suppose you have read a value into an unsigned short int varible named input_data. This data type should be two bytes or 16 bits, but you should check that.
To get the low byte and high byte, use the bitwise "and" operator, &, with suitable bit masks.
lo_byte = input_data & 0xFF;
hi_byte = input_data & 0xFF00;

The first statement above puts the low 8 bits into lo_byte. The second statement puts the high 8 bits into hi_byte.

To get back the number, do this:
number = 256 * hi_byte + lo_byte;
 
Thanks very much! I will try that as soon as I go into uni tomorrow :D Glad you knew what I meant, I'm rubbish at wording things. Thanks again, think that's exactly what I'm looking for :)
 

Similar threads

Back
Top