# Tag: bit-manipulation

## How to do unsigned integer left shift bit operation in Java 1.8 that matches C#?

I’m trying to port some code from C# to Java and I’m stuck on some low-level bit operations. Here is an example snippet that I’m trying to figure out how to translate from C# to Java: Result: So far so good. How do you convert this same thing to Java? So in Java, I naively just tried turning all the

## Determining divisibility of number by 11 for large numbers

I’m looking for a way to determine a large number is divisible by 11 My understanding: (sum of digits at even positions – sum of digits at odd positions) % 11 == 0 ==> yes This works for some examples. Example: 3816 => (3+1) – (8+6) = -10 In case of negative, do we need to consider 2’s complement of

## Convert 4 bytes to an unsigned 32-bit integer and storing it in a long

I’m trying to read a binary file in Java. I need methods to read unsigned 8-bit values, unsigned 16-bit value and unsigned 32-bit values. What would be the best (fastest, nicest looking code) to do this? I’ve done this in c++ and did something like this: But in Java this causes a problem if for example buffer contains a value

## Java storing two ints in a long

I want to store two ints in a long (instead of having to create a new Point object every time). Currently, I tried this. It’s not working, but I don’t know what is wrong with it: And I’m getting the int values like so: Answer y is getting sign-extended in the first snippet, which would overwrite x with -1 whenever

## Bit twiddling for Java or Scala programmers

Does anyone know of good tutorials or even a good book to master bit-level operations? I mean it’s almost clear what every operation does (in Java for instance) or where to find the right documentation, but I’m very new to this topic and I wonder how things like: work (copied from HashMap). I can’t imagine how Integers, Longs or whatever

## Bitwise operator for simply flipping all bits in an integer?

I have to flip all bits in a binary representation of an integer. Given: The output should be What is the bitwise operator to accomplish this when used with an integer? For example, if I were writing a method like int flipBits(int n);, what would go in the body? I need to flip only what’s already present in the number,