简体   繁体   English

屏蔽n个字节

[英]Mask by n bytes

I struggle masking a uint64_t variable by N bytes. 我努力地将uint64_t变量屏蔽了N个字节。 I do not know N but I know it is 8 or less. 我不知道N,但是我知道它是8或更小。 My current code looks like this: 我当前的代码如下所示:

// uint64_t n is given
uint64_t mask;
for( mask = 0x00; n; n--) {
    mask = mask<<8 | 0xFF;
}

for building the mask. 制作口罩。 What am I doing wrong here? 我在这里做错了什么?

Edit: 编辑:
The question was answered. 问题得到了回答。 Anyway, for better understanding: 无论如何,为了更好地理解:

I want a mask like this: 我想要一个这样的面具:

0x000000FF // or:
0x0000FFFF // or:
0x00FFFFFF

to take 1, 2 or more byte from the data. 从数据中取出1、2或更多字节。 As the comments say, my code works! 正如评论所说,我的代码有效! Maybe I had an bug anywere else! 也许我还有一个错误!

It should work, according to the [operator precendence table1]. 根据[操作员优先级表1],它应该可以工作。

Still, it's more clear to write it as: 尽管如此,将其编写为:

mask <<= 8;
mask |= 0xff;

or: 要么:

mask = (mask << 8) | 0xff;

You can also do it with a look-up table, of course. 当然,您也可以使用查找表来完成此操作。

I am not sure if I get the question right, but your mask looks like 我不确定问题是否正确,但您的面具看起来像

0x00000000000000ff
0x000000000000ffff
0x0000000000ffffff
...

I assume that you want something like the following, to mask individual bytes: 我假设您想要以下内容来屏蔽单个字节:

0x00000000000000ff
0x000000000000ff00
0x0000000000ff0000
...

For this, you can use eg the following code: 为此,您可以使用例如以下代码:

for( mask = 0xff; n; n--) {

    // Use the mask HERE
    ...

    mask = mask<<8;
}

You could use this code snippet, to replace the byteno th byte with dest mask, in src : 您可以使用此代码段在src中用dest mask替换byteno个字节:

uint64_t replacemyByte(uint64_t src, uint64_t byteno,uint64_t dest) 
{
    uint64_t shift = (dest << (8 * byteno));
    uint64_t mask = 0xff << shift;
    return (~mask & src) | shift;
}

Or did I get the question wrong? 还是我把问题弄错了?

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

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