在unsigned int类型设置最后`N`位 [英] Set last `n` bits in unsigned int

查看:162
本文介绍了在unsigned int类型设置最后`N`位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置(以最优雅的方式)正是 N uint32_t的的至少显著位?这就是编写一个函数无效setbits(uint32_t的* X,INT N); 。功能应该处理每个 N 0 32

How to set (in most elegant way) exactly n least significant bits of uint32_t? That is to write a function void setbits(uint32_t *x, int n);. Function should handle each n from 0 to 32.

特别值 n ==可32 的处理方式。

推荐答案

如果你的意思是最不显著n位:

If you meant the least-significant n bits:

((uint32_t)1 << n) - 1

在大多数架构,这将不若n为32,所以你可能不得不做出一个特殊情况为:

On most architectures, this won't work if n is 32, so you may have to make a special case for that:

n == 32 ? 0xffffffff : (1 << n) - 1

在64位架构中,(可能)更快的解决方案是投了再下来:

On a 64-bit architecture, a (probably) faster solution is to cast up then down:

(uint32_t)(((uint64_t)1 << n) - 1)

在实际上,这甚至可能更快上的32位架构,因为它避免了支化。

In fact, this might even be faster on a 32-bit architecture since it avoids branching.

这篇关于在unsigned int类型设置最后`N`位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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