How to modify bits in an integer?

These work for integers of any size, even greater than 32 bit: def set_bit(value, bit): return value | (1<<bit) def clear_bit(value, bit): return value & ~(1<<bit) If you like things short, you can just use: >>> val = 0b111 >>> val |= (1<<3) >>> ‘{:b}’.format(val) ‘1111’ >>> val &=~ (1<<1) ‘1101’

The difference between logical shift right, arithmetic shift right, and rotate right

First remember that machine words are of fixed size. Say 4, and that your input is: +—+—+—+—+ | a | b | c | d | +—+—+—+—+ Then pushing everything one position to the left gives: +—+—+—+—+ | b | c | d | X | +—+—+—+—+ Question what to put as X? with a … Read more

Convert bytes to bits in python

Another way to do this is by using the bitstring module: >>> from bitstring import BitArray >>> input_str=”0xff” >>> c = BitArray(hex=input_str) >>> c.bin ‘0b11111111’ And if you need to strip the leading 0b: >>> c.bin[2:] ‘11111111’ The bitstring module isn’t a requirement, as jcollado‘s answer shows, but it has lots of performant methods for … Read more

How to get binary representation of Int in Kotlin

Method 1: Use Integer.toBinaryString(a) where a is an Int. This method is from the Java platform and can be used in Kotlin. Find more about this method at https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int) Note: This method works for both positive and negative integers. Method 2: Use a.toString(2) where a is an Int, 2 is the radix Note: This method … Read more

Why is number of bits always(?) a power of two? [closed]

That’s mostly a matter of tradition. It is not even always true. For example, floating-point units in processors (even contemporary ones) have 80-bits registers. And there’s nothing that would force us to have 8-bit bytes instead of 13-bit bytes. Sometimes this has mathematical reasoning. For example, if you decide to have an N bits byte … Read more

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