简体   繁体   English

定义蒙版的最佳方法

[英]the best way define a mask

I write a function which should extract from unsigned int deferrent sets of bits. 我编写了一个函数,该函数应该从无unsigned int延迟位集中提取。 I want to use a masks for that.I am not sure what is the best way to define such masks. 我想为此使用遮罩,我不确定定义此类遮罩的最佳方法是什么。 For example I need to extract bits 6:14.So I need to define a mask as 111111111 << 6 . 例如,我需要提取6:14位,因此需要将掩码定义为111111111 << 6 My problem is I can't use boost or something like this and standard c/c++ doesn't know to work with binary numbers. 我的问题是我不能使用boost或类似的东西,而标准的c / c ++不知道使用二进制数。 What is possible to do is to use 111111111 as 2^10-1.I am not sure - this is the best (most elegant ) solution.Any advices? 可以做的是将111111111用作2 ^ 10-1。我不确定-这是最好的(最优雅的)解决方案。

大多数人在表示掩码时使用十六进制,例如0xFF,0x0A等。

Let's try to make a bunch of ones first. 让我们尝试先做一些。

One property of a sequence of N ones in binary is that, just like a sequence of nines in decimal, if you add one to it, you get a one followed by a N zeros. 二进制中N个序列的一个属性是,就像十进制中的九个序列一样,如果向其添加一个,则得到一个1,后跟N个零。 We can use the inverse, the fact that if you subtract one from a one followed by N zeros gets you a sequence of N ones, to make that. 我们可以使用相反的事实,即如果您从一个数字中减去一个数字,然后再加上N个零,则会得到一个N个数字序列。

A one followed by N zeros is just 1 shifted right N places. 一个1后跟N个零仅是向右移动N个位置的1。

template <typename Uint>
Uint zigamorph(int n) { // http://catb.org/jargon/html/Z/zigamorph.html
    return 1 << n - 1; // same as 2^n - 1 :)
}

Armed with zigamorphs of any length, you can now get the bits you want from any value easily by using bitwise and. 有了任意长度的zigamorphs,现在您可以通过使用按位与,轻松地从任何值中获取所需的位。

template <typename Uint>
Uint mask_bits(Uint value, int first_bit, int last_bit) { // both inclusive?
    return value & zigamorph<Uint>(last_bit-first_bit+1);
}

Do you have access to the standard library? 您可以访问标准库吗? If so, I would try std::bitset 如果是这样,我会尝试std::bitset

Here is the documentation for it. 是它的文档。

Just use 0x1FF << 6 (if you want 111111111 << 6 ) or 0x3FF << 6 (if you want 2^10-1 << 6). 只需使用0x1FF << 6 (如果您想要111111111 << 6 )或0x3FF << 6 (如果您想要2 ^ 10-1 << 6)。 That's considerably clearer than your binary. 这比您的二进制文件要清楚得多。 As Jerry Coffin points out, you can easily get 2^10 by using 1 << 10 , but I'm not convinced that this is clearer than just using hexadecimal. 正如杰里·科芬(Jerry Coffin)所指出的那样,使用1 << 10可以轻松获得2 ^ 1 << 10 ,但是我不相信这比使用十六进制更清楚。 (For that matter, in some contexts, 0x7FC00 might be perfectly clear. It has the advantage that you see visually exactly where the bits are in the word, and it's easier to pick them out if you have a hex dump.) (因此,在某些情况下, 0x7FC00可能非常清晰。它的优点是您可以从视觉上准确看到字中的位,如果有十六进制转储, 0x7FC00容易将它们取出。)

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

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