How effective get n bits, starting from startPos from the UInt64 Number.
从UInt64 Number的startPos开始,获取n位的效率如何。
i know woh get bit by bit, but i want to do in more effective way.
我知道我会一点一点地得到,但我想以更有效的方式做。
public static ulong GetBits(ulong value, int startPos)
{
int mask = 1 << startPos;
ulong masked_n = value & (ulong)mask;
ulong thebit = masked_n >> startPos;
return (ulong)thebit;
}
2 个解决方案
#1
2
// assuming bit numbers start with 0, and that
// startPos is the position of the desired
// least-significant (lowest numbered) bit
public static ulong GetBits( ulong value, int startPos, int bits )
{
ulong mask = ( ( 1UL << bits ) - 1 ) << startPos;
return ( value & mask ) >> startPos;
}
#2
1
Ok - so let's say (for sanity's sake, let's talk 8-bits) you have:
好的 - 所以让我们说(为了理智,让我们谈谈8位)你有:
10101010
And you want 3 (m) bits starting at bit 2 (n). You you'll need a mask like this:
你想要从第2位(n)开始的3(m)位。你需要这样的面具:
source: 10101010
mask: 00011100
&result: 00001000
So how to generate the mask? We start with 1 and shift it by the number of bits we want (m)
那么如何生成面具?我们从1开始并将它移动我们想要的位数(m)
start: 00000001
start << 3: 00001000
Now we need a three 1's in our mask, so we simply minus one from the last step:
现在我们需要在面具中使用三个1,所以我们在最后一步中减去一个:
00001000 - 1 = 00000111
So we almost have our mask, now we just need to line it up by shifting it by 2 (n)
所以我们几乎有了我们的面具,现在我们只需要通过将它移动2(n)来排列它
00000111 << 2 = 00011100
And we have our answer
我们有答案
#1
2
// assuming bit numbers start with 0, and that
// startPos is the position of the desired
// least-significant (lowest numbered) bit
public static ulong GetBits( ulong value, int startPos, int bits )
{
ulong mask = ( ( 1UL << bits ) - 1 ) << startPos;
return ( value & mask ) >> startPos;
}
#2
1
Ok - so let's say (for sanity's sake, let's talk 8-bits) you have:
好的 - 所以让我们说(为了理智,让我们谈谈8位)你有:
10101010
And you want 3 (m) bits starting at bit 2 (n). You you'll need a mask like this:
你想要从第2位(n)开始的3(m)位。你需要这样的面具:
source: 10101010
mask: 00011100
&result: 00001000
So how to generate the mask? We start with 1 and shift it by the number of bits we want (m)
那么如何生成面具?我们从1开始并将它移动我们想要的位数(m)
start: 00000001
start << 3: 00001000
Now we need a three 1's in our mask, so we simply minus one from the last step:
现在我们需要在面具中使用三个1,所以我们在最后一步中减去一个:
00001000 - 1 = 00000111
So we almost have our mask, now we just need to line it up by shifting it by 2 (n)
所以我们几乎有了我们的面具,现在我们只需要通过将它移动2(n)来排列它
00000111 << 2 = 00011100
And we have our answer
我们有答案