Skip to content

Instantly share code, notes, and snippets.

@mrousavy
Created November 11, 2017 17:58
Show Gist options
  • Save mrousavy/584d1b72cc381f01d6f1af0bbec7343c to your computer and use it in GitHub Desktop.
Save mrousavy/584d1b72cc381f01d6f1af0bbec7343c to your computer and use it in GitHub Desktop.
C++ filestream Input/Output functions for numbers (32bit, 16bit and 8bit reading and writing) with bit flipping (Little -> Big endian)
#pragma once
#include <stdio.h>
#include <fstream>
#include <stdint.h>
inline uint32_t read_big_int(std::fstream &fileStream) {
unsigned char bytes[4];
fileStream.read((char*)bytes, 4);
return (uint32_t)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
}
inline uint16_t read_big_short(std::fstream &fileStream) {
unsigned char bytes[2];
fileStream.read((char*)bytes, 2);
return (uint16_t)((bytes[0] << 8) | bytes[1]);
}
inline uint8_t read_big_byte(std::fstream &fileStream) {
return (uint8_t)fileStream.get();
}
inline void write_big_int(std::fstream &fileStream, uint32_t value) {
unsigned char bytes[4];
bytes[0] = (unsigned char)(value >> 24);
bytes[1] = (unsigned char)(value >> 16);
bytes[2] = (unsigned char)(value >> 8);
bytes[3] = (unsigned char)(value);
fileStream.write((char*)bytes, 4);
}
inline void write_big_short(std::fstream &fileStream, uint16_t value) {
unsigned char bytes[2];
bytes[0] = (unsigned char)(value >> 8);
bytes[1] = (unsigned char)(value);
fileStream.write((char*)bytes, 2);
}
inline void write_big_byte(std::fstream &fileStream, uint8_t value) {
fileStream.put((char)value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment