我试图使用流操纵器解析文件。 但是,作为std::uint8_t的运算符>> overload,来自<istreams> std::uint16_t , std::uint32_t是格式化的输入函数,它会读取一个字符串,并在必要时将其转换为数字。 因此它将解析23到23而不是二进制表示00000010 00000011到515 。
您可以使用带有reinterpret_cast<>的inputstream.read()方法执行此操作:
is.read(reinterpret_cast<char*>(data), sizeof(*data));
现在我的问题 - 是否可以实现覆盖>>操作符的默认行为,以便我可以使用>>运算符读取这样的std:uint类型? 我该如何实现它,如何在运算符之间切换? 如果不可能,您是否知道实现流操纵器进行解析的好方法?
I am trying to parse a file using stream manipulators. However, as the operator>> overload for std::uint8_t, std::uint16_t, std::uint32_t from <istreams> is a formatted input function, it reads a string and if necessary converts it to a number. SO it would parse 23 to 23 and not the binary representation 00000010 00000011 to 515.
You can do this using the inputstream.read() method with a reinterpret_cast<>:
is.read(reinterpret_cast<char*>(data), sizeof(*data));
Now my question - Is it possible to implement to overwrite the default behavior of the >> operator so I can read in such std:uint types using the >> operator? How would I implement it and how can I switch between the operators? And if it is not possible do you know a nice way to implement a stream manipulator to do the parsing?
最满意答案
无法更改标准库提供的operator>>(std::istream&, uintN_t&)重载。
您可以为自己的流类型添加operator>>(my_binary_stream&, uintN_t&)重载,并让它们执行二进制I / O. (您可以轻松地重新使用标准库流对象来支持您的自定义二进制流,例如使用.read()和.write()操作。)
It is not possible to change the operator>>(std::istream&, uintN_t&) overloads provided by the Standard Library.
You can add operator>>(my_binary_stream&, uintN_t&) overloads for your own stream type, and have them perform binary I/O. (You can easily re-use the Standard Library streams objects in support of your custom binary stream, e.g. using their .read() and .write() operations.)
更多推荐
发布评论