c++ - Converting a uint8_t to its binary representation -
i have variable of type uint8_t
i'd serialize , write file (which should quite portable, @ least windows, i'm aiming at).
trying write file in binary form, came accross working snippet:
uint8_t m_num = 3; unsigned int s = (unsigned int)(m_num & 0xff); file.write((wchar_t*)&s, 1); // file = std::wofstream
first, let me make sure understand snippet - takes var (which unsigned char, 1 byte long), converts unsigned int
(which 4 bytes long, , not portable), , using & 0xff
"extracts" least significant byte.
now, there 2 things don't understand:
- why convert
unsigned int
in first place, why can't like
file.write((wchar_t*)&m_num, 1);
orreinterpret_cast<wchar_t *>(&m_num)
? (ref) - how serialize longer type,
uint64_t
(which 8 bytes long)?unsigned int
may or may not enough here.
uint8_t
1 byte, same char
wchar_t
2 bytes in windows, 4 bytes in linux. depends on endianness. should avoid wchar_t
if portability concern.
you can use std::ofstream
. windows has additional version std::ofstream
accepts utf16 file name. way code compatible windows utf16 filenames , can still use std::fstream
. example
int = 123; std::ofstream file(l"filename_in_unicode.bin", std::ios::binary); file.write((char*)&i, sizeof(i)); //sizeof(int) 4 file.close(); ... std::ifstream fin(l"filename_in_unicode.bin", std::ios::binary); fin.read((char*)&i, 4); // output: = 123
this relatively simple because it's storing integers. work on different windows systems, because windows little-endian, , int
size 4.
but systems big-endian, have deal separately.
if use standard i/o, example fout << 123456
integer stored text "123456". standard i/o compatible, takes little more disk space , can little slower.
it's compatibility versus performance. if have large amounts of data (several mega bytes or more) , can deal compatibility issues in future, go ahead writing bytes. otherwise it's easier use standard i/o. performance difference not measurable.
Comments
Post a Comment