C语言 C 中的隐式类型转换(将 32 位无符号转换为 8 位 u int)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3133376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:45:08  来源:igfitidea点击:

Implicit typecasting in C (Converting 32 bit unsigned in to 8 bit u int)

ccasting

提问by Peter

My question looks a lot like

我的问题看起来很像

How to store a 64 bit integer in two 32 bit integers and convert back again

如何将一个 64 位整数存储在两个 32 位整数中并再次转换回来

(I have an unsigned 32 bit I need to put into 4 unsigned 8-bit variables in C)

(我有一个无符号的 32 位,我需要在 C 中放入 4 个无符号的 8 位变量)

but

My question is whether this:

我的问题是这是否:

uint8_t a;
uint32_t b;
a = b;

guarantees that a is filled with the eight rightmost bits, rather than the eight leftmost bits?

保证 a 填充了最右边的八个位,而不是最左边的八个位?

回答by Nikolai Fetissov

Yes. Do either this:

是的。这样做:

uint32_t num32 = 0xdeadbeef;

uint8_t a = num32;       /* 0xef */
uint8_t b = num32 >> 8;  /* 0xbe */
uint8_t c = num32 >> 16; /* 0xad */
uint8_t d = num32 >> 24; /* 0xde */

Or this:

或这个:

union u
{
    uint32_t num32;

    struct
    {
        uint8_t a;
        uint8_t b;
        uint8_t c;
        uint8_t d;

    } bytes;

} converter;

converter.num32 = 0xdeadbeef;

The first example does notdepend on platform endianess, the second does.

第一个例子并不能依赖于平台的字节顺序,第二个

回答by Konrad Rudolph

I don't know what you mean by rightmost and leftmost (endianness?) but C guarantees that awill contain the 8 lower-order (least significant) bits of b. That is, the assignment will be logically equivalent to:

我不知道你说的最右边和最左边(字节序?)是什么意思,但 C 保证a将包含b. 也就是说,赋值在逻辑上等价于:

a = b % ((uint32_t)UINT8_MAX + 1);

回答by kennytm

From the C standard, it is guaranteed that a == b % (max_of_uint8_t + 1), i.e. the least significant 8 bits. In §6.3.1.3 (Signed and unsigned integers):

从 C 标准来看,保证a == b % (max_of_uint8_t + 1),即最低有效 8 位。在 §6.3.1.3(有符号和无符号整数)中:

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  1. 将整数类型的值转换为 以外的其他整数类型时_Bool,如果该值可以用新类型表示,则不变。
  2. 否则,如果新类型是无符号的,则通过重复加或减一个新类型可以表示的最大值来转换该值,直到该值在新类型的范围内。

Use a = b & 0xffif you need to be safe.

a = b & 0xff如果您需要安全,请使用。

回答by Jay

You might look at the union declaration. If you can guarantee the processor/source of data won't change I think you can assume 'endianness'

您可以查看联合声明。如果你能保证处理器/数据源不会改变,我想你可以假设“字节序