C++文本文件读取
所以我需要一点帮助,我目前有一个文本文件,其中包含以下数据:
myfile.txt
-----------
b801000000
我想要做的是将 b801 等数据读取为位,这样我就可以获得
0xb8 0x01 0x00 0x00 0x00.
Current 的值,我正在将该行读入使用以下 typedef 的无符号字符串。
typedef std::basic_string <unsigned char> ustring;
ustring blah = reinterpret_cast<const unsigned char*>(buffer[1].c_str());
我不断失败的地方是现在试图让每个字符 {'b', '8' 等...} 真正成为 { '0xb8', '0x01' 等...}
任何帮助表示赞赏。
谢谢。
So I need a little help, I've currently got a text file with following data in it:
myfile.txt
-----------
b801000000
What I want to do is read that b801 etc.. data as bits so I could get values for
0xb8 0x01 0x00 0x00 0x00.
Current I'm reading that line into a unsigned string using the following typedef.
typedef std::basic_string <unsigned char> ustring;
ustring blah = reinterpret_cast<const unsigned char*>(buffer[1].c_str());
Where I keep falling down is trying to now get each char {'b', '8' etc...} to really be { '0xb8', '0x01' etc...}
Any help is appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我看到两种方法:
将文件打开为
std::ios::binary
并使用std::ifstream::operator>>
提取十六进制双字节使用标志std::ios_base::hex
并提取为两个字节大的类型(如stdint.h
的 (C++0x/C99))之后uint16_t 或等效项)。有关使用 std::stringstream 的示例,请参阅 @neuro 对您的问题的评论。std::ifstream
的工作方式几乎相同。直接访问流迭代器并手动执行转换。更难、更容易出错,也不一定更快,但仍然很有可能。
I see two ways:
Open the file as
std::ios::binary
and usestd::ifstream::operator>>
to extract hexadecimal double bytes after using the flagstd::ios_base::hex
and extracting to a type that is two bytes large (likestdint.h
's (C++0x/C99) uint16_t or equivalent). See @neuro's comment to your question for an example usingstd::stringstream
s.std::ifstream
would work nearly identically.Access the stream iterators directly and perform the conversion manually. Harder and more error-prone, not necessarily faster either, but still quite possible.
strtol 将字符串(需要一个以 null 结尾的 C 字符串)转换为具有指定值的 int根据
strtol does string (needs a nullterminated C string) to int with a specified base
这样做的方式有点肮脏:
运行这个,我得到:
Kind of a dirty way to do it:
Running this, I get: