设置整个字节如果第一个位是1

发布于 2025-01-21 07:57:43 字数 528 浏览 1 评论 0原文

我正在尝试制作程序,例如273(000100010001B)制作4095(111111111111b)

有趣的部分是我的程序适用于第一个迭代,例如17(00010001b)正确返回255(11111111b),但之后的每个字节都不起作用。例如,273(000100010001b)返回61951(1111000111111111b),我无法弄清楚为什么是这样。

这是我的代码

int x,temp, i;
int mask = 15;
scanf_s("%d", &x);
temp = x;
for(i=0;i<4;i++){
    mask<<=i*4;
    if((temp&1)==1){
        x|=mask;
    } else{

    }
    temp>>=4;
    }
printf("%d", x);

I'm trying to make program that will for for example 273(000100010001b) make to 4095(111111111111b).

Funny part is that my program works for first 2 iterations, for example 17(00010001b) correctly returns 255(11111111b) but every byte after that doesn't work. For instance 273(000100010001b) returns 61951(1111000111111111b) and I cant figure out why is that.

Here is my code

int x,temp, i;
int mask = 15;
scanf_s("%d", &x);
temp = x;
for(i=0;i<4;i++){
    mask<<=i*4;
    if((temp&1)==1){
        x|=mask;
    } else{

    }
    temp>>=4;
    }
printf("%d", x);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一笔一画续写前缘 2025-01-28 07:57:43

问题是您在Mask上执行的偏移。您在第1次迭代中将其移至0,在第二个迭代中将其移动4,第三次迭代中的12(4 + 8)等等。

另外,您不会在temp的所有位上应用蒙版。我无法确定您是否故意这样做。

在这里,您是一个固定版本:

int foo(int x) {
/*  ^ I didn't know how to call such function */
    static size_t const mask_size = 4;
    unsigned mask = 15;

    int temp = x;
    for (unsigned i = 0; i < (CHAR_BIT * sizeof(int)) / mask_size; ++i) {
        if ((temp & 1) == 1) {
            x |= mask;
        }
        mask <<= mask_size;
        temp >>= mask_size;
    }

    return x;
}

我的结果是:

in:  17(10) = 10001(2)
out: 255(10) = 11111111(2)
in:  273(10) = 100010001(2)
out: 4095(10) = 111111111111(2)
in:  4369(10) = 1000100010001(2)
out: 65535(10) = 1111111111111111(2)

The issue is the shift you perform on mask. You shift it by 0 on the 1st iteration, 4 on the 2nd, 12 (4 + 8) on the 3rd and so on.

Also, you don't apply the mask over all the bits of temp. I can't tell if you do this on purpose.

Here you are a fixed version:

int foo(int x) {
/*  ^ I didn't know how to call such function */
    static size_t const mask_size = 4;
    unsigned mask = 15;

    int temp = x;
    for (unsigned i = 0; i < (CHAR_BIT * sizeof(int)) / mask_size; ++i) {
        if ((temp & 1) == 1) {
            x |= mask;
        }
        mask <<= mask_size;
        temp >>= mask_size;
    }

    return x;
}

My results are:

in:  17(10) = 10001(2)
out: 255(10) = 11111111(2)
in:  273(10) = 100010001(2)
out: 4095(10) = 111111111111(2)
in:  4369(10) = 1000100010001(2)
out: 65535(10) = 1111111111111111(2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文