在C#中以32位正整数交换位 [英] Swapping bits in a positive 32bit integer in C#

查看:102
本文介绍了在C#中以32位正整数交换位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试解决这个问题:

So I'm trying to solve this problem:

您将获得随机的32位正整数,而您要做的是将第3、4和5位的值与第24、25和26位的值交换.

You are given random 32bit positive integer, and what you have to do is swap the values of the bits on 3rd, 4th and 5th positions with those on 24th, 25th and 26th position.

推荐答案

假定您不希望对此问题有明确的解决方案,那么这里提示:使用&屏蔽有问题的位,然后执行移位,然后按OR键,然后按位|键.

Assuming that this is a problem for which you do not want an explicit solution, here is a hint: mask the bits in question using &, do a shift, and then OR then in using bitwise |.

您可以使用0x00000034掩码切出"第3、4和5位,而使用0x07000000掩码切出"第24、25和26位.

You can "cut out" bits 3, 4, and 5 using the 0x00000034 mask, and bits 24, 25, and 26 using the 0x07000000 mask.

看看这个解决方案,以解决反转问题的灵感

Take a look at this solution to bit reversing problem for an inspiration.

(针对不是家庭作业"的评论)由于这不是家庭作业,因此这里有更深入的说明:

EDIT : (in response to "not a homework" comment) Since this is not a homework, here is a more in-depth explanation:

unsigned int val = ... // your value
unsigned int bits_03_04_05 = val & 0x00000034;
unsigned int bits_24_25_26 = val & 0x07000000;
// Cut out "holes" at bits 3, 4, 5, 24, 25, and 26 of the original value
unsigned int res = val & ~(0x00000034 | 0x07000000);
// Put bits 3, 4, and 5 in place
res |= bits_03_04_05 << 21;
// Put bits 23, 24, and 25 in place
res |= bits_24_25_26 >> 21;

这篇关于在C#中以32位正整数交换位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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