Using bitwise operators in C++ to change 4 chars to int -


What should I do, which opens a file in binary mode that contains the stored data that is interpreted as integers I have seen such other examples, but I want to try to take a different approach (I might just be stubborn, or stupid: /) I had previously created a simple binary file in a hex editor, which reads as follows.

00 00 47 00 00 00 17 00 00 00 41 This is (required) is equal to 71, 23 and 65, if 12 bytes were divided into 3 integers.

After opening this file in binary mode and reading four bytes, in an array of characters, how do I perform bitwise actions to create [0] bits around each bits of each variable are part of int Integer = 00 00 00 00 ^ ^ ^ Characters four [0] four [1] variables [2] four [3] 00 00 00 then my integer (hex) = 00 00 00 47 = numeric value 71

Besides, I do not know how my system's endlessness plays here, so anything like that Land should I remember?

Even though I have a code snippet so far, I do not know how to take the next step now.

  std :: fstream myfile; Myfile.open ("C: \\ User \\ Jacob \\ Desktop \\ hextest.txt", std :: IOS :: | | std :: IOS :: out | std :: IOS :: binary); If (myfile.is_open () == incorrect) {std :: cout & amp; Amp; Lt> Error & amp; Amp; & Amp;; & Lt; Std :: endl; } Four * mirror; Std :: cout & amp; Lt myfile.is_open () & amp; Lieutenant; & Lt std :: endl; Motor = new four [4]; Myfile.read (mychar, 4);   

I'm finally planning to read float from a file and maybe at the end of a custom data type, but first I need to be more familiar to do a bit of work Thank you .

You want bitwise left shift operator:

  int number = (Characters [0] << 24) + (Characters [1]   

What this does is move the left argument to a certain number of bits on the left, adding zero to the right as a filler, for example, 2 < & Lt; 1 is 4, changes 2 to 10 in the binary and on the left one returns 100 , which is 4.

This can be more written in a more general loop form:

  int num = 0; For (int i = 0; i! = 4; ++ i) {num + = character [i] & lt; & Lt; (24 - I * 8); // | = Can also be used}   

The endlessness of your system does not matter here; You know the endlessness of representation in the file, which is continuously (and therefore portable), so when you read in bytes, you know what to do with them. The internal representation of an integer in your CPU / memory may differ from file, but its logical bitwar manipulation in the code is independent of the endlessness of your system; At least the critical bits are always correct, and at the far left (in the code). This is the reason that the transfer is the inter-stage - it operates at the logical bit level: -)

Comments