Now that c++17 has std::byte
, I was looking for a way to convert code that reads files to char
into code that reads files into byte
. A file contains bytes, not a bunch of integers.
Then I read this question and this other question where people argued that reading files into byte
is wrong, and that reading files into char
is right.
If byte
is not designed for the purpose of accessing memory, and by analogy, files, then what is the its purpose? As is quoted in the other two questions:
Like char and unsigned char, it can be used to access raw memory occupied by other objects (object representation), but unlike those types, it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and only bitwise logic operators are defined for it.
This sounds like the exact type that should be used for reading files, not characters.
byte
is correct, but C++ iostreams are not direct access to files, they automatically perform conversion. Your OS file access API will probably work fine withbyte
pointers. – Frumpyunsigned char*
or astd::byte*
? – Epistd::byte
is a more expressive name when you just want to store/read/write some bytes. I don't think I'll ever use it (except if someone could give us an enlightening answer), asunsigned char
is fine for me – Cochabambai & (i-1)
which also only want to perform bit operations. – Dicotyledonstd::byte
. (one could argue that there should be aclearLowestBit(std::byte)
function for this, though, which casts internally - but I don't really see the benefit of forbidding usual operations on a byte, like addition) – Cochabambastd::byte
already represents well, that it's not a numerical value. I think, there's no need to forbid certain operations on it. Where's the benefit? Makes us to make less mistakes? I don't think so. And your example makes sense. Here,i-1
isn't actually a numerical operation, but used as a bit operation (though a complex one: it sets the trailing zeros to one (here, we don't need this behavior, but it's harmless), and the lowest set bit to zero)... – Cochabambastd
functions. – Cochabamba