[C++] Converting Binary Data to Types

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Schmacker
    New Member
    • May 2007
    • 5

    [C++] Converting Binary Data to Types

    Hi there,

    I'm trying to teach myself some things about random file I/O with binary, and have come across a task that I am unsure I know how to approach.

    Currently I write out a bunch of variable length structs to a binary file. They look something like this

    Code:
    struct testStruct
    {
       std::string term;
       unsigned long termCount;
    };
    When writing out I am writing the length of the string before I write the string, as an unsigned long, so that I can know how long the string will be. After writing out 10 of theses to disk, I then read all 10 back in as a single chunk of binary data, using ifstream.read() , and store it in a char array.

    What I want to do is then go through this array and, for want of a better term, extract the actual types and data out of the array. I have tried casting, but that just truncates, and I have tried bit shifts, but I think that I don't understand those well enough to actually make it work.

    Can someone suggest a way to do this? Is bit shifting a good approach? Is there something that I haven't mentioned that could be used? It would be much appreciated.

    Thanks,
    Dylan Jenkinson
  • Schmacker
    New Member
    • May 2007
    • 5

    #2
    Never mind, I figured out what I was doing wrong.

    Thanks

    Comment

    • sicarie
      Recognized Expert Specialist
      • Nov 2006
      • 4677

      #3
      Care to post what it was in case someone runs into a similar issue?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Most likely the data was written out in constant sized blocks. There's no random access of variable sized blocks.

        Comment

        Working...