未设置在一个字(INT32)[℃]的最显著位 [英] Unset the most significant bit in a word (int32) [C]

查看:171
本文介绍了未设置在一个字(INT32)[℃]的最显著位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能取消设置一个字的最高显著设置好的比特(例如0x00556844 - > 0x00156844)?有一个 __ builtin_clz 在海湾合作委员会,但它只是计数为零,这是不需要我。另外,我应该如何更换__builtin_clz的MSVC或英特尔C编译器?

How can I unset the most significant setted bit of a word (e.g. 0x00556844 -> 0x00156844)? There is a __builtin_clz in gcc, but it just counts the zeroes, which is unneeded to me. Also, how should I replace __builtin_clz for msvc or intel c compiler?

目前我的code是

 int msb = 1<< ((sizeof(int)*8)-__builtin_clz(input)-1);
 int result = input & ~msb;

更新:好吧,如果你说,这code是相当快的,我就问你,我该怎么加移植到这个code?这个版本是GCC,但MSVC和放大器; ICC?

UPDATE: Ok, if you says that this code is rather fast, I'll ask you, how should I add a portability to this code? This version is for GCC, but MSVC & ICC?

推荐答案

刚轮下降到2最近的电源,然后XOR与原始值,例如使用 flp2() 的喜悦:

Just round down to the nearest power of 2 and then XOR that with the original value, e.g. using flp2() from Hacker's Delight:

uint32_t flp2(uint32_t x) // round x down to nearest power of 2
{
    x = x | (x >> 1); 
    x = x | (x >> 2); 
    x = x | (x >> 4); 
    x = x | (x >> 8); 
    x = x | (x >>16); 
    return x - (x >> 1); 
}

uint32_t clr_msb(uint32_t x) // clear most significant set bit in x
{
    msb = flp2(x);  // get MS set bit in x
    return x ^ msb; // XOR MS set bit to clear it
}

这篇关于未设置在一个字(INT32)[℃]的最显著位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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