开发者

Reading/Writing integer values on a string object

I have the contents of a file assigned into a string object. For simplicity the file only has 5 bytes, which is the size of 1 integer plus another byte. What I want to do is get the first four bytes of the string object and somehow store it into a valid integer variable by the program. Then the program will do various operations on the integer, changing it. Afterward I want the changed integer stored back into the first four bytes of the string object.

Could anyone tell me I could achieve this? I would prefer to stick with the standard C++ library exclusively for开发者_Python百科 this purpose. Thanks in advance for any help.


The following code snippet should illustrate a handful of things. Beware of endian differences. Play around with it. Try to understand what's going on. Add some file operations (binary read & write). The only way to really understand how to do this, is to experiment and create some tests.


#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    int a = 108554107; // some random number for example sake

    char c[4];            // simulate std::string containing a binary int
    *((int *) &c[0]) = a; // use casting to copy the data

    // reassemble a into b, using indexed bytes from c
    int b = 0;
    b |= (c[3] & 0xff) << 24;
    b |= (c[2] & 0xff) << 16;
    b |= (c[1] & 0xff) << 8;
    b |= c[0] & 0xff;

    // show that all three are equivalent
    cout << "a: " << a << " b: " << b
        << " c: " << *((int *) &c[0]) << endl;

    return 0;
}


If you are reading into std::string from that file any zero byte would signal end of the string, so you might end up with a string that is shorter then 5 bytes. Take a look here for how to do binary I/O with C++ streams.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜