简体   繁体   English

位操作 - 仅改变最后4位

[英]bit manipulation - only change last 4 bits

I want to set the last 4 bits of an int to another int. 我想将int的最后4位设置为另一个int。

So for example you have this int: 1100 0001 . 例如,你有这个int: 1100 0001 And I only want to change the last four bits with another int for example: 0000 0110 . 我只想用另一个int更改最后四位,例如: 0000 0110 All the other bits should remain unchanged and it has to be in one statement (I'm sorry for my horrible explanation). 所有其他位应该保持不变,它必须在一个声明中(我很抱歉我的可怕解释)。

The folowing statement does work, but it seems bad practice and It would only work with an uint8_t 下面的声明确实有效,但它看起来很糟糕,它只适用于uint8_t

unint8_t count = 6; //0000 0110
PORTC = ((PORTC >> 4) << 4) | count; //PORTC = 1100

The outcome of PORTC is 1100 0110 and this is what I want, however I want it to work with any integer. PORTC的结果是1100 0110 ,这就是我想要的,但是我想让它适用于任何整数。 What is another (better) way of doing this? 这样做的另一种(更好)方法是什么?

NOTE: It must be one statement. 注意: 必须是一个声明。

您首先要使用掩码设置AND目标号码,该掩码除了设置4个最低位以外,然后使用与第一个数字的最低4位的OR。

PORTC = (PORTC & ~0xfULL) | ( count & 0xf );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM