Search code examples
c++sequencebit

How do i use the fixed sized integers from 'cstdint' lib to store/pack bit data sequence with maximum length of 250MB? Why to not use normal int?


In the condition of the task that I am doing, I am specifically told: "Integers in C++ do not have a fixed size. To access integers with a fixed size, you can use the library cstdint." I take it it is recommended that I use fixed-sized integers for packing of bit data (max 250MB). I am failing to understand how does fixed-sized int help in this case? And how do I use those fixed-sized integers? I imagine I should probably declare a structure, but I am not at all sure. Thank you!


Solution

  • Integers in c++ are not fixed size in that they can have different sized based on arch or other environment variables (OS, compiler, etc.)

    The library cstdint exposes data type that are guaranteed to be fixed in size, for example the type int8_t is guaranteed to be 8 bit long, and you can use uint8_t to read/write your data.

    Example in reading to/from a file

    #include <cstdint>
    #include <iostream>
    #include <fstream>
    
    int main() {
        //writing
        uint8_t value = '8';
        std::ofstream myoutputfile;
        myoutputfile.open("filename");
        myoutputfile << value << std::endl;
        myoutputfile.close();
        
        //reading
        std::ifstream myinputfile;
        myinputfile.open("filename");
        uint8_t c;
        myinputfile >> c;
        std::cout << c;
        myinputfile.close();
        return 0;
        
    }
    

    if i wanted to write a small (<100KB) quantity of data i'd do something like:

    uint8_t data[5] = { '1', '2', '3', '4', '5' };
    
    //writing
    myoutputfile.open("filename");
    for (int i = 0; i < 5; i++) {
        myoutputfile << data[i];
    }
    myoutputfile.close();
    
    //reading
    myinputfile.open("filename");
    for (int i = 0; i < 5; i++) {
        myinputfile >> data[i];
        std::cout << data[i];
    }
    myinputfile.close();