位操作,置换位 [英] Bit manipulation, permutate bits

查看:81
本文介绍了位操作,置换位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个循环,遍历所有不同的整数,其中最后40位中的10位恰好设置为高,其余设置为低.原因是我有一个包含40个不同值的映射,并且我想对所有不同的方式求和,可以将这些值中的十个相乘. (这只是出于好奇,因此真正引起关注的是"bitmanip"循环,而不是总和.)

I am trying to make a loop that loops through all different integers where exactly 10 of the last 40 bits are set high, the rest set low. The reason is that I have a map with 40 different values, and I want to sum all different ways ten of these values can be multiplied. (This is just out of curiosity, so it's really the "bitmanip"-loop that is of interest, not the sum as such.)

如果我要这样做,例如4位中的2位,很容易手动进行设置,

If I were to do this with e.g. 2 out of 4 bits, it would be easy to set all manually,

0011 = 3,
0101 = 5,
1001 = 9,
0110 = 6,
1010 = 10,
1100 = 12,

但是在40个中有10个我似乎找不到有效生成这些的方法.我尝试从1023(二进制为1111111111)开始,找到了一种很好的方法来操纵它,但没有成功.我一直在尝试用C ++做到这一点,但实际上是感兴趣的通用方法(如果有的话).我进行了一些谷歌搜索,但是如果有人之间建立了良好的联系,那么收效甚微,当然也将不胜感激. :)

but with 10 out of 40 I can't seem to find a method to generate these effectively. I tried, starting with 1023 ( = 1111111111 in binary), finding a good way to manipulate this, but with no success. I've been trying to do this in C++, but it's really the general method(if any) that is of interest. I did some googling, but with little success, if anyone has a good link, that would of course be appreciated too. :)

推荐答案

稍微复杂一点,但是纯粹是通过位操作来完成的.您的示例:

A bit more complicated, but done purely by bit manipulation. Your example:

#define WIDTH 4
#define BITS 2

void printbits(long pattern) {
  long bit;
  for (bit = 1L << WIDTH - 1; bit; bit >>= 1)
    putchar(pattern & bit ? 49 : 48);
  putchar('\n');
}

void movebits(pattern, bit) {
  long mask = 3L << bit;
  while (((pattern ^= mask) & mask) && (mask < 1L << WIDTH)) {
    mask <<= 1;
    printbits(pattern);
    if (bit)
      movebits(pattern, bit - 1);
  }
}

int main() {
  long pattern = (1L << BITS) - 1L, mask;
  printbits(pattern);
  movebits(pattern, BITS - 1);
}

您的实际应用程序:

#define WIDTH 40
#define BITS 10

并且,正如多基因润滑剂所说,准备等待:)当然,您将用对您更有用的东西代替printbits ...

and, as polygenelubricants says, be prepared to wait for bit :) Of course, you will replace printbits with something more useful to you...

(由于测试不足而/该死的错别字...)

(Edited for insufficient testing :/ Damn typos...)

这篇关于位操作,置换位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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