Changing integer to binary string of digits

There are actually standard one-liners for these. #include <bitset> std::string s = std::bitset< 64 >( 12345 ).to_string(); // string conversion std::cout << std::bitset< 64 >( 54321 ) << ‘ ‘; // direct output std::bitset< 64 > input; std::cin >> input; unsigned long ul = input.to_ulong(); See this run as a demo.

Why does a byte only have 0 to 255?

Strictly speaking, the term “byte” can actually refer to a unit with other than 256 values. It’s just that that’s the almost universal size. From Wikipedia: Historically, a byte was the number of bits used to encode a single character of text in a computer and it is for this reason the basic addressable element … Read more

“grep” offset of ascii string from binary file

grep –byte-offset –only-matching –text foobar filename The –byte-offset option prints the offset of each matching line. The –only-matching option makes it print offset for each matching instance instead of each matching line. The –text option makes grep treat the binary file as a text file. You can shorten it to: grep -oba foobar filename It … 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’

How are integers internally represented at a bit level in Java?

Let’s start by summarizing Java primitive data types: byte: Byte data type is an 8-bit signed two’s complement integer. Short: Short data type is a 16-bit signed two’s complement integer. int: Int data type is a 32-bit signed two’s complement integer. long: Long data type is a 64-bit signed two’s complement integer. float: Float data … Read more

What is “two’s complement”?

Two’s complement is a clever way of storing integers so that common math problems are very simple to implement. To understand, you have to think of the numbers in binary. It basically says, for zero, use all 0’s. for positive integers, start counting up, with a maximum of 2(number of bits – 1)-1. for negative … Read more