Skip to content

Instantly share code, notes, and snippets.

@ramunas
Last active November 9, 2019 20:17
Show Gist options
  • Save ramunas/577952c1139e8eba03f48aa59a94638c to your computer and use it in GitHub Desktop.
Save ramunas/577952c1139e8eba03f48aa59a94638c to your computer and use it in GitHub Desktop.
#include <cstdint>
#include <iostream>
using namespace std;
/*
* Returns the bits in range msb to lsb from bits. The returned bits are
* shifted to the least signifcant bit. The bits are ordered from most to
* least signifcant bit; where the most signifcant bit has the index <number of
* bits> - 1 and the least has 0.
*
* The range is inclusive [msb,lsb]. E.g., bits(x, 1, 1) returns the second
* bit.
*
* For example, let x = 10011010, then bits(x, 4, 1) = 00001101.
*/
template <typename T> inline T bits(T bits, size_t msb, size_t lsb) {
T ones = ~static_cast<T>(0);
return (~(ones << ((msb + 1) - lsb))) & (bits >> lsb);
}
template <typename T>
inline T assign_bits(T bits, size_t msb, size_t lsb, T value) {
size_t size = msb - lsb + 1;
T ones = ~static_cast<T>(0);
T v = (~(ones << size) & value) << lsb;
T clear_mask = ~(~(ones << size) << lsb);
T r = bits & clear_mask;
return r | v;
}
template <typename T> void print_bits(T b) {
int size = sizeof(T) * 8;
for (int i = size - 1; i >= 0; i--) {
cout << (int)bits(b, i, i);
}
cout << endl;
}
class BitString {
public:
int length;
BitString() {}
};
int main() {
uint32_t x = ~static_cast<uint32_t>(0);
auto b = bits(x, 1, 0);
cout << x << " = " << b << endl;
uint8_t a = 4;
print_bits(a);
for (int i = 0; i < 16; i++) {
print_bits(assign_bits((uint16_t)0, i + 1, i, (uint16_t)3));
}
cout << endl;
uint64_t alter = 0;
for (int i = sizeof(alter) * 8 - 1; i >= 0; i--) {
if (i % 2 == 1) {
alter = assign_bits(alter, i, i, (uint64_t)1);
}
}
print_bits(alter);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment