Skip to content

Instantly share code, notes, and snippets.

@9re
Created January 25, 2012 13:32
Show Gist options
  • Save 9re/1676263 to your computer and use it in GitHub Desktop.
Save 9re/1676263 to your computer and use it in GitHub Desktop.
reading integer from network stream
all: StreamReader.hpp test.cpp
g++ -o test test.cpp
#include <endian.h>
#include <string.h>
#include <iostream>
namespace {
template <typename T>
union TypeCaster
{
T data;
char bytes[sizeof(T)];
};
template <typename T, int>
struct ByteOrder_ {
static inline T convert(T val);
};
template<typename T>
struct ByteOrder_<T, 2> {
static inline T convert(T val) {
return htobe16(val);
}
};
template<typename T>
struct ByteOrder_<T, 4> {
static inline T convert(T val) {
return htobe32(val);
}
};
template<typename T>
struct ByteOrder_<T, 8> {
static inline T convert(T val) {
return htobe64(val);
}
};
template<typename T>
struct ByteOrder {
static inline T convert(T val) {
return ByteOrder_<T, sizeof(T)>::convert(val);
}
};
} // namespace
template<typename T>
struct StreamReader
{
inline static T read(std::istream &in) {
int size = sizeof(T);
TypeCaster<T> caster;
in.read(caster.bytes, size);
return ByteOrder<T>::convert(caster.data);
}
};
#include <assert.h>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <string>
#include "StreamReader.hpp"
int main(void) {
std::istringstream is("12345678");
assert (StreamReader<int32_t>::read(is) == 0x31323334);
assert (StreamReader<int32_t>::read(is) == 0x35363738);
is.seekg(0, std::ios::beg);
assert (StreamReader<int64_t>::read(is) == 0x3132333435363738);
is.seekg(3, std::ios::beg);
assert (StreamReader<int16_t>::read(is) == 0x3435);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment