suggestions for changing some bit of a number

hello
I use miracle library to work with big numbers.
I defined a number for example X with 192 bit. at first X= 0 ;
I want to change for example 3 bit of it to 1 randomly.
as a example:
assume that X has 10 bit :
X=0000000000
random numbers should be :
1000010001
1010100000
1100000100
...
...
how can I do it ?
best Regards
You can use so called masks.

1
2
//Binary number 10-bit
X=0b0000000000;


then a mask with a value of 8
1
2
3
Y=0b0000001000;
or
Y=(1<<3);


And add them together (OR them) - turn bit High
X |= Y;

Or substract them (AND inverse mask) - turn bit Low
X &= ~Y;

Or switch the bit H->L or L-H depending on value of X (XOR them)
X ^= Y;

Note 1: I am not certain if binary numbers (0b00) are part of C++ standard. You may instead use hexadecimal numbers (0x00) or shift left/right operators (<</>>)
Note 2: Try to search for binary operation and operators.

Some pseudocode for your example
1
2
3
4
uint16_t X=0x0000; //16-bit unsigned number - 10-bit is odd
for(int i=0; i<3; ++i){
  X |= 1 << RANDOM_INT(0,15);
}


Also I am not sure if this works for n-bit variables. So far I only used it for 8-bit microcontrollers.
Topic archived. No new replies allowed.