assembly,optimization,bit-manipulation,division,multiplication

That method is called, "Division by Invariant Multiplication". The constants that you're seeing are actually approximates of the reciprocal. So rather than computing: N / D = Q you do something like this instead: N * (1/D) = Q where 1/D is a reciprocal that can be precomputed. Fundamentally, reciprocals...

c++,bit-manipulation,bit,bitwise-operators

From Wikipedia: The bitwise AND operator is a single ampersand: &. It is just a representation of AND which does its work on the bits of the operands rather than the truth value of the operands. Bitwise binary AND does the logical AND (as shown in the table above) of...

Basically all you have to do is: shift everything right by n bits using right shift: >> shift the bits you want to rotate all the way to the left: << Combine the shifted right and shifted left bits with or: | See this code for an example implementation using...

In your code n |= (n & 0X0000) | 0x6000; is wrong beacuse of is equal to 0xABCDE98 & 0x0000 = 0 and 0x0000 | 0x6000 = 0x6000 and 0xABCDE98 | 0x6000 = 0xABCFDE98 Instead you must write n = (n & 0XFFF0FFF) | 0x6000; ...

swift,int,boolean,type-conversion,bit-manipulation

@martin-r’s answer is more fun :-), but this can be done in a playground. // first check this is true or you’ll be sorry... sizeof(Bool) == sizeof(UInt8) let t = unsafeBitCast(true, UInt8.self) // = 1 let f = unsafeBitCast(false, UInt8.self) // = 0 ...

Reason's very simple: the mask value might start at something like 128, then be right-shifted to 64, 32, etc.. So, in... if ((mask & bit) == 0 ){ ...if the masked bit is set the bitwise AND will return the mask bit, and everything works as hoped. But in... if...

the single ampersand means both conditions are checked It means the bitwise AND of the two operands is computed. As one of the operands has only a single bit set, only one condition is being checked: OP_READ. so, in this case key.readyOps() will return a number whose bits represent...

There are three basic approaches for extracting encoded information from a bitfield. The first two are related and differ only in the manner the bitfield struct is initialized. The first and shortest is to simply create a bitfield struct defining the bits associated with each member of the struct. The...

c,integer,compare,bit-manipulation,string-comparison

It's possible to do this using bit-manipulation. Space your values out so that each takes up 5 bits, with 4 bits for the value and an empty 0 in the most significant position as a kind of spacing bit. Placing a spacing bit between each value stops borrows/carries from propagating...

ruby,integer,bit-manipulation,byte

Here's something that may help you: def rbit(n) r = 0 8.times{|i| r = r * 2 + n[i] } r end Credit Reverse bit order of 32 bit integers by mark-hubbart Or if you prefer bit operators, something like this: def rbit(n) (((n & 0x01) << 7) |((n &...

c++,bit-manipulation,bit-shift,bitwise-or,bitboard

You need to use 1LL as 64 bit value before you use shift operator << to get 64 bit result: #include <stdint.h> uint64_t kings = 0ULL; kings |= 1ULL << i; ...

It has an effect because 200 is beyond the maximum possible (signed) byte, 127. The value is already assigned -56 because of this overflow. The most significant byte, worth -128, is set. 11001000 The first 2 output statements show -56 because of this, and the fact that casting to a...

You can do this using strtr function: $bites = array("1", "00101", "101", "0000"); $output = array_map(function($element){ return strtr($element, array('1', '0')); }, $bites); print_r($output); ...

objective-c,c,bit-manipulation,bitwise-operators

This value is not binary. It is octal. uint8_t sizeOfGlobalColorTable = 010; In (Objective) C constants starting from 0 are interpreted as octal values. What you actually write is b1000 & b0111 = 0. It should be: uint8_t sizeOfGlobalColorTable = 0x2; ...

You did your two's complement wrong. It would actually be: 1111...1011 So ...1011 & ...0101 = 1....

java,bit-manipulation,unary-operator

There in nothing wrong with the ~ operator. It does flip the bits. All you have to understand, is that in Java, int value are always signed. But since “unsigned” is only a matter of interpretation of the bits, you have to print them like unsigned values, e.g. using Java 8:...

Iterate over all the bytes of the struct and XOR each one individually, e.g., void bytexor(unsigned char xor_byte, void *data, size_t size) { unsigned char *p = data; while (size--) { *p++ ^= xor_byte; } } Usage would be: struct triple my_struct; // ... bytexor(0xFF, &my_struct, sizeof my_struct); (Note: This...

c,bit-manipulation,machine-code

Shifting the bit width or more is undefined behavior. The first pass, counter = 8 attempts currentIns = currentIns | (c << 32);. Assuming currentIns is a 32-bit integer, this is undefined behavior. The typical undefined behavior in this case is only a shift of (counter * 4)%32 occurs. With...

c++,bit-manipulation,pseudocode

You are using logical AND: MT[i] = ((1812433253*(MT[i-1]^(((MT[i-1]))>>30)))+i) && 0xffffffff; You want to use bitwise AND: MT[i] = ((1812433253*(MT[i-1]^(((MT[i-1]))>>30)))+i) & 0xffffffff; The first expression will give you either true (if the first value is nonzero) or false. The second expression will give you the lowest 32 bits of that value....

You need to use the &H hexadecimal literal: result = (&HF8F Xor &HFB8E) 62465 ...

Consider casting as providing a different layout stencil on memory. Using this stencil picture, the code is a layout of a stencil of 32-bits on an unsigned integer memory location. So instead of treating the memory as a uint32_t, it is treating the memory as 32 bits. A pointer to...

javascript,node.js,bit-manipulation,tostring,parseint

In JavaScript, all bitwise operations (and & among them) return signed 32-bit integer as a result, in the range −231 through 231−1, inclusive. That's why you have that extra bit (0xde000000 is greater than 0x7ffffff) representing a sign now, meaning that you get a negative value instead. One possible fix:...

inline int clz_u128 (uint128_t u) { uint64_t hi = u>>64; uint64_t lo = u; int retval[3]={ __builtin_clzll(hi), __builtin_clzll(lo)+64, 128 }; int idx = !hi + ((!lo)&(!hi)); return retval[idx]; } this is a branch free variant. Note that more work is done than in tye branchy solution, and in practice the...

algorithm,for-loop,bit-manipulation,modulus

well I do not see any point in your code ... but there are many ways how to create repetitive series you need here few examples example1: int tab[4]={0,1,0,2}; for (int i=0;i<8;i=(i+1)&3) output(tab[i]); use a table example2: for (int i=0;i<8;i+=4) { output(0); output(1); output(0); output(2); } direct output ...

java,arrays,bit-manipulation,xor

In the version that works for all inputs you are using longs to hold the counters : long oCount = 0, eCount = 0; In the version that doesn't work for some inputs, you are using ints to hold the counters : int oddCount = 0, evenCount = 0; Perhaps...

c,syntax,bit-manipulation,bitwise-operators

Shift operator only only works on integral types. Using << causes implicit integral promotion, type casting b to an int and "protecting" the higher bits. To solve, use temp = ((unsigned char)(b << 4)) >> 4;...

Do you mean something like this: public int getInt(int input){ return (1<<input)-1; } Lets say input=5 then 1<<input (1<<5) is binary 100000 Then it needs to decrease only to 11111 its 31 in decimal...

In JS all bitwise operators are signed 32bit, whereas your result is unsigned 32bit. As a workaround you could calculate it as: var res = ints.reduce(function(result, current) { return result * 256 + current; }, 0); // 4278190335 which is even nicer in ES2015: var res = ints.reduce((result, current) =>...

Alright, I have it figured out. First, some terminology: blocker mask: A bitboard containing all squares that can block a piece, for a given a piece type and the square the piece is on. It excludes terminating edge squares because they always block. blocker board: A bitboard containing occupied squares....

c,x86,integer,bit-manipulation,sse

The right way to think about the throughput limits of integer multiplication using various instructions is in terms of how many "product bits" you can compute per cycle. mulx produces one 64x64 -> 128 result every cycle; that's 64x64 = 4096 "product bits per cycle" If you piece together a...

c++,c,memory,bit-manipulation,information-theory

You should be able to do what you said using 4 bytes. Assume that you store the 20 values into a single int32_t called value, here is how you would extract any particular element: element[0] = value % 3; element[1] = (value / 3) % 3; element[2] = (value /...

Just mask and shift. You've already got a comment describing the format: // Message identifiers are constructed: // Unit Type Bit 8-10 // Board ID Bit 5-7 // Unit Specific Message Ids Bit 0-4 So the reversal code is: int messageId = identifier & 0x1f; int boardId = (identifier >>...

arrays,set,bit-manipulation,bitwise-operators

You can look at it from a different perspective: pick a power of two. Can we generate it? This question is easy to answer. Take all items from the set in which the bit corresponding to the power of two is set. Calculate the AND of all of those. The...

$b = 0000 0000 0000 0000 0000 0000 0000 1100 ~$b = 1111 1111 1111 1111 1111 1111 1111 0011 = -13 Note that PHP uses the two's complement representation which means that the most significant bit is the sign bit, here '1' refers to '-'. You can read more...

python,python-3.x,bit-manipulation

Your whole approach doesn't make sense in Python. The number of 1 bits in -17621, aka -100010011010101 binary, is 7. If you're expecting 26, you're not asking for the number of 1 bits in the number, you're asking for the number of 1 bits in the C 32-bit 2's complement...

This answer makes the following assumptions. Bits are numbered from 1, the first bit is the MS bit of the first byte. The extracted bit array must be left-aligned. Unused bits on the right are padded with 0. #include <stdio.h> #include <string.h> #include <limits.h> #define MAX_LEN 60 #define BMASK (1...

c,bit-manipulation,bitwise-operators,stm32

Bits are 0-indexed, but you coded the shifts as if bits were 1-indexed instead. You have to use 0 through 7 for the shifts on a uint8_t. Also, the right-shifts can be removed. Try this: void FP_UpdateData(FP_BUTTONS *data, uint8_t b1, uint8_t b2) { data->button_1 = (b1 & ( 1 <<...

x & 0xFF means "The least significant byte of x" (x & 0xFFFF) >> 8 means "The second least significant byte of x" When written one after another, it represent (short)x (i.e the 2 least significant bytes of x) in little endian....

Python (even Python 2) do not enforce integer subtypes. You could loop up to 48 (instead) of 32, and Python would automatically convert the number to a long, and you would get 281474976710654L. It would be more explicit if you were printing repr(result) on Python 2.x because you would get...

What about: void shiftSet(unsigned long x){ //Function to shift all set bits to the left //Precondition: x is a hexidecimal number //Postcondition: all set bits in x are shifted to the left most bit placements unsigned int count; for (count = 0; x; count++) x &= x - 1; //...

java,bit-manipulation,shift,operations

Let's say that a = 0011 1100 So with the Binary Left Shift Operator (<<). The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 So in your code you have a loop...

java,algorithm,integer,bit-manipulation

Your first iteration changes the left most bit from 0 to 1. This is the sign bit, so of course you got a negative number. EDIT : change evaluateBit = (c >> k); to evaluateBit = (c >> k) & 1; In order for evaluateBit to really contain the value...

The idea here is that you are iterating through the int values that represent the powers of two starting at 128 down to 1. Then the & binary operator is used to isolate the binary bit for the given power of 2. So for t = 128 the binary representation...

What you are missing is that in C++ right shift >> is implementation defined. It could either be logical or arithmetic shift for a signed value. In this case it's shifting in 1s from the left to retain the sign of the shifted value. Typically you want to avoid doing...

Well, as mentioned, str is not an integer. It's a pointer, as it is being dereference with * operator. *((str) + 3) is equivalent to *(str + sizeof(str[0])*3), thus this depends on the type of str, as seen here. Same goes for other dereference operator. So what's going on? Well,...

java,android,bit-manipulation,bitwise-operators

I assume that you want to perform a bitwise operation on strings(which performs a bitwise operation on ASCII values of characters of these string in PHP). There is no such operator for String in Java, but you can do it using BitSet: public String or(String a, String b) throws UnsupportedEncodingException...

For integers only, you can get there in a slightly devious way with the following: def justify(n): return n / 1<<(n.bit_length()-1) I've no idea if it's faster without significant testing but a quick test with timeit shows it to be about twice as fast as your first snippet. However, converting...

c#,.net,enums,bit-manipulation

You could compare the bitwise OR of enum values with the arithmetic sum of enum values: var values = Enum.GetValues(typeof(EnumWithoutUniqueFlags)) .OfType<EnumWithoutUniqueFlags>().Select(val => (int)val).ToArray(); bool areBitsUnique = values.Aggregate(0, (acc, val) => acc | val) == values.Sum(); EDIT As the @usr mentioned, the code above works for positive values only. Despite the...

c#,.net,bit-manipulation,bit-shift

One way might be something like: ulong mask = ((1 << length) - 1) << offset; I'm not clear why you even want the bitoffset value, but that should simply be a matter of shifting by your offset value, right? E.g.: ulong bitoffset = 1 << offset; ...

python,numpy,bit-manipulation,bit,bitstring

I'm not sure if you want to count the number of "1" bits or to check wether a specific bit is set. To check, I guess the easier way is: bool(n&(1<<b)), where n is the number being tested and b is the bit (starting from 0). To count the number...

It is creating the binary representation for the IP 192.43.244.18. Let's analyse each operation one by one. Start from the binary representation of those constants: 192 = 11000000 43 = 00101011 244 = 11110100 18 = 00010010 Innermost operation: (192 << 8) = = 11000000 << 8 = = 1100000000000000...

c++,c,bit-manipulation,bitwise-operators

You can also do this with XOR and bit masking. #include <stdio.h> void f(unsigned val, unsigned ary[3]) { ary[0] = val; ary[1] = (ary[0] ^ 1) & 1; ary[2] = (ary[0] ^ 2) & 2; } int main() { unsigned ary[3] = {0}; f(0, ary); printf("f(0) = %d %d %d\n",...

c++,return,bit-manipulation,ampersand

Here is what it means: The initial x part means x != 0 The (x & (x-1)) part means "x is not a power of two" (i.e. is zero or has more than one bit set) The !(x & (x-1)) expression means "x is a power of two" Therefore, overall...

It's based on three observations, The bitcount of a single bit is that bit itself. The bitcount of the concatenation of two bitstrings is the sum of their bitcounts. The bitcount of any string takes no more bits than that string itself. The first two points together give you a...

From the 32 bit int, you want to keep the 19 most significant, so discard the 13 least; then you shift right by 13 bits, but have to get rid of the possible sign extension, by anding with a 19 bit pattern: (myint >> 13) & 0x7ffff ...

Read Bit twiddling hacks. Even if the answer isn't in there, you'll be better educated on bit twiddling. Also, the original code is simply setting the bits in the range; toggling means turning 1 bits into 0 bits and vice versa (normally achieved using ^ or xor). As to the...

Shift the value x bits to the right and then use AND to restrict the number of bits you use. ie: (n >> 8) & 0xff or (n >> 16) & 0xff.

I would go with performing Arithmetic Right Shift(till the length of the binary number) two at a time. This >> used in my logic is for arithmetic shift. (Note: In C language, right shifts may or may not be arithmetic!) Like, int count=0; bit=extractLastbit(binary_representation_of_the_number); while(count!=binaryLength){ // binaryLength is the length...

c,bit-manipulation,bitwise-operators,firmware

It's not possible in a single instruction. This is because there are 3 possible operations you need to do on the different bits: Set them (bit 3) Clear them (bit 4) Leave them alone (all the other bits) How can you select from one of three possibilities with a bitmask...

There is no such helper in redigo. Here is my implementation: func hasBit(n byte, pos uint) bool { val := n & (1 << pos) return (val > 0) } func getBitSet(redisResponse []byte) []bool { bitset := make([]bool, len(redisResponse)*8) for i := range redisResponse { for j:=7; j>=0; j-- {...

java,type-conversion,bit-manipulation,byte,long-integer

java's byte type is signed, so 0xff (255) == -1, during extending from byte to int/long - signed value is preserved, so if you just have code: final byte a = (byte)0xff; final long b = a; System.out.println(b); // output here is -1, not 255 so, here comes one trick:...

I believe you can do this using java.math.BigInteger which supports shifts on arbitrarily large numbers. This has advantage of simplicity, but disadvantage of not padding into original byte array size, i.e. input could be 16 bytes but output might only be 10 etc, requiring additional logic. BigInteger approach byte []...

double,bit-manipulation,point,floating

I agree with the comment that it should be done in binary, rather than by conversion to decimal and decimal multiplication. I used Exploring Binary to do the arithmetic. The first step is to find the actual binary significands. Neither input is subnormal, so they are 1.000101 and 1.00100001. Multiply...

python,c++,algorithm,data-structures,bit-manipulation

This is a job for the sqrt decomposition. We want to maintain state that allows us to answer the current range and to adjust endpoints of the current range up or down one. To that end, we maintain a map from element to (sum of all indexes of that element...

c,bit-manipulation,bitwise-operators,bit-shift

Two things: image[i] & mask1 only checks whether image[i] and mask1 have at least one bit in common. Is this your intention? first_hline_first_row &=~ (0<<i); does nothing (~(0<<i) is all ones). From the comments I'm guessing that this is what you meant to write: for(i=0; i<16; i++){ if(image[i] & mask1)...

Here's a solution which uses only 7 operations. Note that this works even when i == j. uint64_t swapbits(uint64_t n, size_t i, size_t j) { uint64_t x = ((n >> i) ^ (n >> j)) & 1; // x = 1 bit "toggle" flag return n ^ ((x << i)...

c++,bit-manipulation,operators

According to your code I'd bet on a stackoverflow due to infinite recursion if you try to print negative values. void print(int stackCallIndex, int nb) { if(number) { print(++stackCallIndex, nb >> 1); // likely an infinite recursion here. if(nb & 1) printf("%d", 1); else printf("%d", 0); if(stackCallIndex % 8 ==...

c,bit-manipulation,bitwise-operators,bitwise-and

& is the bitwise AND operator. here, (x & z) == z means, perform a bitwise AND of x and z and if that value equals to z, then.... Ref: Chapter 6.5.10, C11 standard, "Bitwise AND operator" The result of the binary & operator is the bitwise AND of the...

c,bit-manipulation,micro-optimization

Only slightly cheating: int bang(int x) { return ((x ^ 0xffffffffU) + 1UL) >> 32; } is the only way I can think of to do it in only 3 operations. Assumes a 32-bit int and 64-bit long......

There is one clever trick to check if byte has more one bit set. n & (n - 1) != 0

SOLUTION After searchs and searchs I found this and I re-convert in PHP function BitwiseAndLarge($val1, $val2) { $shift = 0; $result = 0; $mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones) $divisor = 1 << 30; // To work with the bit mask,...

c,binary,double,bit-manipulation,arc4random

When I print the binary representations of i and *(&i+1) and compare them to the binary representation of d, d is composed by appending *(&i+1) and i. So *(&i+1) comes first?! Why is this the case? the actual ordering of the bytes depends upon the 'Endian-ness' of the underlying...

performance,cryptography,bit-manipulation,bit-shift,javacard

When it comes for speed, known length, hard-coded version is the fastest (but ugly). If you need to shift more than one bit, ensure to update the code accordingly. output[0] = (byte)((byte)(input[0] << 1) | (byte)((input[1] >> 7) & 1)); output[1] = (byte)((byte)(input[1] << 1) | (byte)((input[2] >> 7) &...

Shift operations are performed using a CPU register. The register consists of a number of bits (8, 16 and 32 are common, and you appear to have a 32 CPU), which in combination can be interpreted as a decimal value. In your example you use the value 1. The C...

int gzipHeader = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); The type byte is Java is signed. If you cast a byte to an int, its sign will be extended. The & 0xff is to mask out the 1 bits that you get from sign extension, effectively...

java,algorithm,bit-manipulation

All you need really is this: public int updateBits(int n, int m, int i, int j) { int mask = ((int)((1L<<(j-i+1))-1))<<(i); return (n&~mask)|((m<<i)&mask); } Note that for debugging purpose, you can use following method to print out the bit string: System.out.println(Integer.toBinaryString(mask)); Basically I need to create a mask that matches...

a is an int and so is the literal a&0xaaaa. The result of the bitwise-and operation is also int. It has 32 bits. With a&0xaaaa you have masked out all but the lowest few bits from a. The result is a positive, 32-bit int value. So by printing out the...

c#,bit-manipulation,bitwise-and

Assuming that you want to work with the enums directly, the base types of all enums are integers. With this knowledge, you can take the "unbounded" nature of integers and bring the goodness of enums. enum Greetings { HELLO = 1, WORLD = 2, AND = 4, SO = 8,...

javascript,syntax,bit-manipulation

You're on the right way - the single pipe in JavaScript stands for a bitwise or. You can find the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#.7c_%28Bitwise_OR%29

Using bitwise operator how can I test if the n least significant bits of an integer are either all sets or all not sets. To get a mask for the last n significant bits, thats (1ULL << n) - 1 So the simple test is: bool test_all_or_none(uint64_t val, uint64_t...

c,bit-manipulation,standards,bit

In general, it's not that hard to accommodate unusual platforms for the most cases (if you don't want to simply assume 8-bit char, 2's complement, no padding, no trap, and truncating unsigned-to-signed conversion), the standard mostly gives enough guarantees (a few macros to inspect certain implementation details would be helpful,...

"Efficient" can mean a different things here: e.g., asymptotic vs performance for a known range of inputs; time vs space; etc. I'll assume you care about raw speed for the small bounded inputs you describe. Baseline approach. Take the smaller bit, and left shift it until it's equal to the...

python,c++,algorithm,bit-manipulation

The binary, 2's complement representation of -4 is ...11100 Yes, I really do mean infinitely many 1's to the left; this is a binary repeating numeral. Technically, 4 is a repeating numeral too: ...00100 it's just repeating 0's to the left. Your addition problem is ...11100 + ...00100 -------------------- ...00000...

c#,bit-manipulation,byte,bytearray,implicit-conversion

result is already a byte[], so do this instead: BitArray b = new BitArray(result); The part that's actually causing the problem is this: new byte[] { result } The reason for this is because the array initializer needs to take expressions that are compatible with the element type of the...

With an unsigned shift, x = n >>> 31; // Java's unsigned shift x = (int)((uint)n >> 31); // C#'s unsigned shift, the casts are effectively nop GCC does this automatically, other compilers may also. Or not. Your mileage may vary....

assembly,bit-manipulation,mainframe

ICM R7,B'1111',FIRSTBUF LOAD 4 BYTES FROM FIRSTBUF INTO REGISTER 7 SLL R7,2 ; Shift away zeros LR R8,R7 ; Move to a work register AND R8, 0x3F ; Clear out extra bits. ; First Character complete. SLL R7,8 ; Remove 1 character and lower 2 bit 0s by shifting...

y = ( x + 1 + (x>>8) ) >> 8 // very fast This is a fixed-point approximation of division by 255. Conceptually, this is useful for normalizing calculations based on pixel values such that 255 (typically the maximum pixel value) maps to exactly 1. It is described as...

matlab,bit-manipulation,octave

That or is equivalent to an addition when dealing with integers result = bitshift(bi2de(bitget(a,1:2)),8) + b; e.g a = 01010111 b = 10010010 result = 00000011 100010010 = a[2]*2^9 + a[1]*2^8 + b an alternative method could be result = mod(a,2^x)*2^y + b; where the x is the number of...

You can do it in two steps: First, use XOR to find all bits that have toggled: int allToggled = oldValue ^ newValue; Then mask the bit that you want to keep - for example, by shifting allToggled to the right, so that the target bit is at position zero,...

c#,.net,binary,bit-manipulation,endianness

Well the math for an Int16 would just be: public Int16 SwitchEndianness(Int16 i) { return (Int16)((i << 8) + (i >> 8)); } or if you have a 2-byte array: public Int16 SwitchEndianness(byte[] a) { //TODO: verify length return (Int16)((a[0] << 8) + a[1]); } but you'll have to try...

java,algorithm,bit-manipulation,xor,bitwise-xor

Note: please read the explenation, simply solving challenges by copy-pasting the answer is not useful. The constraint you can exploit is that The first bit is untouched by the encryption algorithm. Indeed because all "masks" are shifted at least one to the right. So you can assume that the first...