How many bits is a “word”?

I’m not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor. Processors have been made with quite a variety of word sizes, not always a multiple of 8. The 8086 and 8087 processors used 16 bit words, and it’s likely this is …

Read more

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’

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