How does Python’s bitwise complement operator (~ tilde) work?

Remember that negative numbers are stored as the two’s complement of the positive counterpart. As an example, here’s the representation of -2 in two’s complement: (8 bits) 1111 1110 The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts … Read more

Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting long to int?

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. An example cited from §15.26.2 […] the following code is … Read more

How to get defined operators for a type in .net

Get the methods with Type.GetMethods, then use MethodInfo.IsSpecialName to discover operators, conversions etc. Here’s an example: using System; using System.Reflection; public class Foo { public static Foo operator +(Foo x, Foo y) { return new Foo(); } public static implicit operator string(Foo x) { return “”; } } public class Example { public static void … Read more

What does the ‘%’ operator mean?

It is the modulo (or modulus) operator: The modulus operator (%) computes the remainder after dividing its first operand by its second. For example: class Program { static void Main() { Console.WriteLine(5 % 2); // int Console.WriteLine(-5 % 2); // int Console.WriteLine(5.0 % 2.2); // double Console.WriteLine(5.0m % 2.2m); // decimal Console.WriteLine(-5.2 % 2.0); // … Read more