修改uint32_t变量的位

时间:2015-03-23 23:53:38

标签: c++ bits uint32

我有一个uint32_t变量,我想修改randombly前10个不太重要的位(0-9)然后,仍然是随机的,我想修改第10到第23位。我用C ++编写了这个简单的程序,它适用于前10位但不适用于其他程序。我不明白为什么

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <math.h>

using namespace std;

void printuint(uint32_t value);

int main(){

    uint32_t initval=0xFFFFFFFF;
    uint32_t address;
    uint32_t value;
    uint32_t final;


    address=rand()%1024;
    address<<=23;
    printf("address \n");
    printuint(address);

    printf("final\n");
    final = (initval & address);
    printuint(final);


    return 0;
}

void printuint (uint32_t value){

    while (value) {
        printf("%d", value & 1);
        value >>= 1;
    }
    cout<<endl;
}

添加此

    value = rand() % 16384;
    printuint(value);

并修改final = (initval & address) & value;

2 个答案:

答案 0 :(得分:0)

以下是翻转随机位的示例:

int main(void)
{
  srand(time());
  unsigned int value = 0;
  for (unsigned int iterations = 0;
       iterations < 10;
       ++iterations)
  {
    unsigned int bit_position_to_change = rand() % sizeof(unsigned int);
    unsigned int bit_value = 1 << bit_position_to_change;
    value = value ^ bit_value;  // flip the bit.
    std::cout << "Iteration: " << iterations
              << ", value: 0x" << hex << value
              << "\n";
  }
  return EXIT_SUCCESS;
}

operator ^表示的异或功能适用于翻转位。

另一种方法是替换位:

unsigned int bit_pattern;
unsigned int bit_mask; // contains a 1 bit in each position to replace.
value = value & ~bit_mask;  // Clear bits using the mask
value = value | bit_pattern;  // Put new bit pattern in place.

答案 1 :(得分:0)

抱歉,我更耐心地解决了我的问题。

我打算这样做:

    uint32_t initval;

    uint32_t address(1023);
    bitset<32> bits(address);
    cout << bits.to_string() << endl;

    uint32_t value(16383);
    value<<=10;
    bitset<32> bitsvalue(value);
    cout << bitsvalue.to_string() << endl;

    initval = address | value;
    bitset<32> bitsinit(initval);
    cout << bitsinit.to_string() << endl;

    return 0;