[英]modify bits of uint32_t variable
我有一個uint32_t變量,我想隨機地修改前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;
這是翻轉隨機位的示例:
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.
抱歉,我更加耐心地解決了我的問題。
我的意思是這樣的:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.