Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to write and read 8 bits from a file in C++

1 Answer

0 votes
#include <fstream>
#include <cstdint> // For uint8_t
#include <bitset>
#include <iostream>

int main() {
    // write
    std::ofstream outFile("data.bin", std::ios::binary); // Open file in binary mode
    if (!outFile) {
        return 1; // Handle error
    }

    uint8_t bytewrite = 0b10101110; // Example 8-bit data
    outFile.write(reinterpret_cast<const char*>(&bytewrite), sizeof(bytewrite)); // Write 1 byte
    outFile.close();

    // read
    std::ifstream inFile("data.bin", std::ios::binary); // Open file in binary mode
    if (!inFile) {
        return 1; // Handle error
    }

    uint8_t byteread;
    inFile.read(reinterpret_cast<char*>(&byteread), sizeof(byteread)); // Read 1 byte
    inFile.close();

    std::cout << "Read byte: " << std::bitset<8>(byteread) << std::endl; // Display as binary

    return 0;
}




/*
run

Read byte: 10101110

*/

 



answered Jul 30, 2025 by avibootz
...