Bit operation
#1

Hi, I need help with bit operations..
Lets say I have all bits "turned on"

Код:
11111111111111111111111111111111
Now I have variables ex.

Код:
new myVar = 8;
And I must turn off 8th bit and get something like

Код:
11111110111111111111111111111111
I tried

Код:
new data; // all bits off
new myVar1 = 2, myVar2 = 8, myVar3 = 12;
data |= myVar1; // turn on 2nd bit
data |= myVar1; // turn on 12th bit

print((data & myVar1) ? ("myVar1 passed") : ("myVar1 failed"));
print((data & myVar2) ? ("myVar2 passed") : ("myVar2 failed"));
print((data & myVar3) ? ("myVar3 passed") : ("myVar3 failed"));

// Out: 
[20:49:25] myVar1 passed
[20:49:25] myVar2 failed
[20:49:25] myVar3 failed
Reply
#2

bump
Reply
#3

Read through this https://sampforum.blast.hk/showthread.php?tid=177523
Reply
#4

Код:
11111110111111111111111111111111
This is not the 8th bit.

If you try to "turn off" a specify bit, you can't do it with the OR logical operation because 1 OR 0 = 1 everytime.
You need to use AND logical operator with NOT.

PHP код:
main()
{
    new 
test_value 0b1111111111// there is 10, 1
    
test_value &= ~(<< 7); // 8-1
    
printf("%b"test_value);

Reply
#5

Quote:
Originally Posted by RakeDW
Посмотреть сообщение
Hi, I need help with bit operations..
Lets say I have all bits "turned on"

Код:
11111111111111111111111111111111
Now I have variables ex.

Код:
new myVar = 8;
And I must turn off 8th bit and get something like

Код:
11111110111111111111111111111111
I tried

Код:
new data; // all bits off
new myVar1 = 2, myVar2 = 8, myVar3 = 12;
data |= myVar1; // turn on 2nd bit
data |= myVar1; // turn on 12th bit

print((data & myVar1) ? ("myVar1 passed") : ("myVar1 failed"));
print((data & myVar2) ? ("myVar2 passed") : ("myVar2 failed"));
print((data & myVar3) ? ("myVar3 passed") : ("myVar3 failed"));

// Out: 
[20:49:25] myVar1 passed
[20:49:25] myVar2 failed
[20:49:25] myVar3 failed
First off, 8 fails because you didn't set it.
Furthermore you use myVar1 twice and expect it to do different things (but in fact you set the 2nd twice).

Your test should be:

Код:
data |= myVar1; // turn on 2nd bit
data |= myVar2; // turn on 8th bit
data |= myVar3; // turn on 12th bit
But even that isn't correct as Dayrion said. Your test was just wrong additionally to the operations.

Also 8 wouldn't set the 8th bit. 8 in binary is not equal to b10000000. 8 is b1000.
12 is also two bits that get set. It's b1100
Reply
#6

Fixed it.
Код:
 
new some_var;
new bit_pos_to_turn_on = 15;
some_var |= (1 << bit_pos_to_turn_on);

printf((some_var & (1 << bit_pos_to_turn_on)) ? ("pass") : ("fail"));
anyway thanks to all
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)