std :: byte的目的是什么? [英] What is the purpose of std::byte?

查看:124
本文介绍了std :: byte的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在c ++ 17具有 std :: byte ,我正在寻找一种将读取文件的代码转换为 char的方法转换为将文件读取到 byte 的代码中。文件包含字节,而不是一堆整数。

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.

然后我阅读了此问题另一个问题,其中有人争辩说将文件读入 byte 是错误的,而将文件读入 char 是正确的。

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.

如果 byte 并非为访问内存而设计的(以此类推),那么它的目的是什么?如其他两个问题所述:

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:


类似于char和unsigned char,它可用于访问其他对象(对象表示)占用的原始内存
,但与那些
类型不同,它不是字符类型,不是算术类型。
字节只是位的集合,并且仅为其定义了按位逻辑运算符

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 非常适合访问内存。当存储只是一个字节序列而不是一个字符数组时,您打算使用该类型。

byte is very much intended for "accessing memory". You are intended to use the type when the storage is just a sequence of bytes rather than an array of characters.

Iostream类型不能专用于字节,因为它们是围绕字符设计的接口。就是说,他们不认为文件是字节序列。他们认为它们是字符序列。现在,您当然可以通过使用一两个强制转换直接读入 byte 数组。但这不是iostream固有的思维方式。

Iostream types cannot be specialized with byte, since they're designed around characters as their interface. That is, they do not think of files as sequences of bytes; they think of them as sequences of characters. Now, you can certainly read directly into a byte array by using a cast or two. But that's not the way iostream natively thinks.

您必须在iostream的工作方式与文件的工作方式之间进行区分。毕竟,Iostream只是一个文件IO库。

You have to make a distinction between the way iostream works and the way files work. Iostream is just one file IO library, after all; it is hardly the end-all, be-all of file APIs.

大多数用于读取二进制数据的文件API都使用 void * 而不是字符数组。 std :: fread / fwrite ,依此类推。

Most file APIs for reading binary data take void* rather than character arrays. std::fread/fwrite, and so forth.

也就是说,您应该考虑这一点,而不是 std :: byte 有问题,而 iostream 有问题。一长串中的另一个。

That is, you should think of this, not as a problem with std::byte, but as a problem with iostream. Just another in a long line of them.

这篇关于std :: byte的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆