用于在 ANSI (C89/90) C 中表示字节的类型? [英] Type to use to represent a byte in ANSI (C89/90) C?

查看:18
本文介绍了用于在 ANSI (C89/90) C 中表示字节的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有符合标准的方法来表示 ANSI (C89/90) C 中的字节?我知道,大多数情况下,char 恰好是一个字节,但我的理解是,不能保证情况如此.另外,C99标准中有stdint.h,但是C99之前用的是什么?

我对 8 位和一个字节"(sizeof(x) == 1)很好奇.

解决方案

char 总是一个 byte ,但它并不总是一个 octet.字节是内存的最小可寻址单位(在大多数定义中),八位字节是内存的 8 位单位.

也就是说,sizeof(char)对于所有的实现总是1,但是limits.h中的CHAR_BIT宏code> 定义平台的字节大小,并不总是 8 位.有16位和32位字节的平台,因此char会占用更多位,但它仍然是一个字节.由于 char 的要求范围至少为 -127 到 127(或 0 到 255),因此在所有平台上至少 8 位.

<块引用>

ISO/IEC 9899:TC3

6.5.3.4 运算符的大小

  1. ...
  2. sizeof 运算符产生其操作数的大小(以字节为单位),它可以是表达式或括号内的类型名称.[...]
  3. 当应用于类型为 charunsigned charsigned char(或其限定版本)的操作数时,结果是 1.[...]

强调我的.

Is there a standards-complaint method to represent a byte in ANSI (C89/90) C? I know that, most often, a char happens to be a byte, but my understanding is that this is not guaranteed to be the case. Also, there is stdint.h in the C99 standard, but what was used before C99?

I'm curious about both 8 bits specifically, and a "byte" (sizeof(x) == 1).

解决方案

char is always a byte , but it's not always an octet. A byte is the smallest addressable unit of memory (in most definitions), an octet is 8-bit unit of memory.

That is, sizeof(char) is always 1 for all implementations, but CHAR_BIT macro in limits.h defines the size of a byte for a platform and it is not always 8 bit. There are platforms with 16-bit and 32-bit bytes, hence char will take up more bits, but it is still a byte. Since required range for char is at least -127 to 127 (or 0 to 255), it will be at least 8 bit on all platforms.

ISO/IEC 9899:TC3

6.5.3.4 The sizeof operator

  1. ...
  2. The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. [...]
  3. When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. [...]

Emphasis mine.

这篇关于用于在 ANSI (C89/90) C 中表示字节的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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