Data Type Truncation

2020-05-03 02:15发布

I have a basic C question.

Suppose I've declared and initialized a standard 16 bit unsigned integer

uint16_t var1 = 0x1234;

and then suppose I declared an 8 bit unsigned integer:

uint8_t var2;

If I were to assign,

var2 = var1;

would this be a valid statement? And would it simply truncate the more significant bits yielding a result such that:

var2 == 0x34

evaluates to true?

标签: c
2条回答
家丑人穷心不美
2楼-- · 2020-05-03 02:46

Yes. The compiler would internally interpret this as

var2 = (uint8_t)var1;

which would result in var2 having the value 0x34.

查看更多
成全新的幸福
3楼-- · 2020-05-03 03:04

I think you mean:

uint16_t var1 = 0x1234;
uint8_t var2;
var2 = var1;

Yes, this will truncate var1 to fit within var1's data type, so var2 will be equal to 0x34.

查看更多
登录 后发表回答