Overview
A binary digit or bit is a 0
or 1
character. A bit string is then a contiguous sequence of bits. It’s weight is a reference to the number of 1
s in the bit string. Compare the below operation to the method for converting from one numerical base to another (e.g. hexadecimal).
unsigned int bit_weight(int64_t n) {
unsigned int count = 0;
while (n) {
count += (n % 2 == 0) ? 0 : 1;
n /= 2;
}
return count;
}
Endianness
Platforms with multi-byte objects must establish the object’s address and byte ordering. Objects are typically addressed by the smallest address of the bytes used. Bytes are ordered either in big-endian or little-endian. In big-endian, the most significant byte is listed first. In little-endian, the least significant byte is ordered first.
#include <stdint.h>
#include <stdio.h>
int main() {
int32_t x = 0x01234567;
for (int i = 0; i < 4; ++i) {
printf("%.2x ", ((unsigned char *)(&x))[i]);
}
}
The above snippet can be used to check endianness on the current machine. If big-endian, the output should be 01 23 45 67
. If little-endian, 67 45 23 01
.
Bibliography
- Bryant, Randal E., and David O’Hallaron. Computer Systems: A Programmer’s Perspective. Third edition, Global edition. Always Learning. Pearson, 2016.