I have 5 bit numbers like
10000 01000 00100
If only one bit is included in my calculation, I have no problem.
but if 2 bits are on, then I want to select only the first bit, for example
10010
I want to treat it as 2 instead of the number 18
is there a bitwise operation that i can use in such a setting?
Since you only want to isolate it, don't get its index, it's easy:
function firstSetBit(number) { return number & -number; }
, , , , , , , . , " ", , , , . , , .
log2 (n & -n) + 1;
.
. , "1". :
function filterFirstFoundBit(number) { for (var i = 0; i < 32; i++) { if ((1 << i) & number) { return 1 << i; } } return number; } document.write(filterFirstFoundBit(9)); //10010
function isolateLowestBit(input) { mask = 1; while (mask <= input) { if (mask & input) { // found match - mask is set to the value of the lowest bit return mask; } mask *= 2; // shift up mask by one bit } // no match return 0; }
Beware that bitwise operations in Javascript is a bad idea, because since Javascript numbers are not natural integers.
Source: https://habr.com/ru/post/1686773/More articles:Laravel 5.3 cookies not created in browser - sessionThe value of x & (-x) in 2 additions? - bit-manipulationUIDocumentInteractionController does not open another application in iOS 11 - iosLaravel 5.2.11, sessions do not work, session cookie is not set - phpHow to configure netcoreapp2.0 and net461 in the same project - c #Spring Kafka Consumer Replay - spring-bootЕсть ли способ отменить опцию? - rustУказанный режим заполнения недействителен для этого алгоритма - С# - System.Security.Cryptography - securityPJSIP: Crash on pj_sockaddr_get_port when moving an iOS application in the background and then in the foreground - iosQuick order - setAll Articles