How can I detect integer overflow on 32 bits int?

Math.addExact throws exception on overflow Since Java 8 there is a set of methods in the Math class: toIntExact(long) addExact(int,int) subtractExact(int,int) multiplyExact(int,int) …and versions for long as well. Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range. Example of addition: int x = … Read more

Fastest way to clamp a real (fixed/floating point) value?

Both GCC and clang generate beautiful assembly for the following simple, straightforward, portable code: double clamp(double d, double min, double max) { const double t = d < min ? min : d; return t > max ? max : t; } > gcc -O3 -march=native -Wall -Wextra -Wc++-compat -S -fverbose-asm clamp_ternary_operator.c GCC-generated assembly: maxsd … Read more

Convert 0x1234 to 0x11223344

This can be done using SSE2 as follows: void ExpandSSE2(unsigned __int64 in, unsigned __int64 &outLo, unsigned __int64 &outHi) { __m128i const mask = _mm_set1_epi16((short)0xF00F); __m128i const mul0 = _mm_set1_epi16(0x0011); __m128i const mul1 = _mm_set1_epi16(0x1000); __m128i v; v = _mm_cvtsi64_si128(in); // Move the 64-bit value to a 128-bit register v = _mm_unpacklo_epi8(v, v); // 0x12 -> … Read more

Mod of power 2 on bitwise operators?

He meant that taking number mod 2^n is equivalent to stripping off all but the n lowest-order (right-most) bits of number. For example, if n == 2, number number mod 4 00000001 00000001 00000010 00000010 00000011 00000011 00000100 00000000 00000101 00000001 00000110 00000010 00000111 00000011 00001000 00000000 00001001 00000001 etc. So in other words, number … Read more

Bitfield manipulation in C

Bitfields are not quite as portable as you think, as “C gives no guarantee of the ordering of fields within machine words” (The C book) Ignoring that, used correctly, either method is safe. Both methods also allow symbolic access to integral variables. You can argue that the bitfield method is easier to write, but it … Read more

Checking flag bits java

To check to see if a bit value is set: int value = VALUE_TO_CHECK | OTHER_VALUE_TO_CHECK; if ((value & VALUE_TO_CHECK) == VALUE_TO_CHECK) { // do something–it was set } if ((value & OTHER_VALUE_TO_CHECK) == OTHER_VALUE_TO_CHECK) { // also set (if it gets in here, then it was defined in // value, but it does not … Read more

Unsigned Integer in Javascript

document.write( (1 << 31) +”<br/>”); The << operator is defined as working on signed 32-bit integers (converted from the native Number storage of double-precision float). So 1<<31 must result in a negative number. The only JavaScript operator that works using unsigned 32-bit integers is >>>. You can exploit this to convert a signed-integer-in-Number you’ve been … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)