gpt4 book ai didi

c - 不同类型如何存储在内存中

转载 作者:IT王子 更新时间:2023-10-28 23:35:26 26 4
gpt4 key购买 nike

我目前正在编写一个涉及处理字节的 C 程序。说到字节,我真的很困惑以下问题。

  1. 字符是否通过它们的 ascii 代码存储在内存中?假设“A”的 anscii 代码为 65。所以它在内存中的存储方式与整数 65 相同?

  2. 如果是,机器如何区分字符和整数?

  3. 如果字符是用 ascii 码存储的,那么 ascii 码就是一个整数。一个整数至少要占2个字节,怎么一个字符只占1个字节?

  4. 最后一个是关于不同架构上的整数。在 16 位机器上,如果 1 存储为 000...0001,那么在 32 位机器上,1 是否仍以前面加 0 的方式存储?

最佳答案

Are characters stored in memory by their ascii codes? Say 'A' has anscii code 65. So it's stored in memory the same way as integer 65?

是的,但是 C 中的 char 是单个字节,而 int 取决于机器架构。

If so, how does the machine distinguish a character and an integer?

机器代码不关心内存中的字节代表什么。编译器的工作是把你的代码翻译成机器指令来执行你的程序。

If characters are stored by ascii codes, an ascii code is an integer. An integer should occupy at least 2 bytes, how come a character only occupy 1 byte?

ASCII可以容纳在单个字节中(这是 char 的大小)。在 C 中处理非 ASCII 文本更为复杂。有 wchar_t 是不可移植的,许多人认为它已损坏。 C11引入char16_tchar32_t,可分别用于UTF-16和UTF-32。

The last one is about integers on different architectures. On a 16-bit machine, if 1 is stored as 000...0001, then on a 32-bit machine, is 1 still stored the same way just adding 0 at the front?

这大部分是正确的,但也取决于 endianness架构。

关于c - 不同类型如何存储在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21693685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com