Created
August 27, 2018 14:52
-
-
Save Sam-Belliveau/8db7de48cd8ed545805e12262228bbd6 to your computer and use it in GitHub Desktop.
This lets you do bit manipulation in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef BITMANIPULATION_H | |
| #define BITMANIPULATION_H | |
| #include <cstdint> | |
| template<class T> | |
| inline bool getBit(const T& input, const std::size_t& bit) | |
| { | |
| const T bitMask = 0x1 << bit; | |
| return (input & bitMask) != 0x0; | |
| } | |
| template<class T> | |
| inline T& flipBit(T& input, const std::size_t& bit) | |
| { | |
| const T bitMask = 0x1 << bit; | |
| input = input ^ bitMask; | |
| return input; | |
| } | |
| template<class T> | |
| inline T& enableBit(T& input, const std::size_t& bit) | |
| { | |
| const T bitMask = 0x1 << bit; | |
| input = input | bitMask; | |
| return input; | |
| } | |
| template<class T> | |
| inline T& disableBit(T& input, const std::size_t& bit) | |
| { | |
| if(getBit(input, bit)) | |
| { | |
| flipBit(input, bit); | |
| } | |
| return input; | |
| } | |
| template<class T> | |
| inline T& setBit(T& input, const std::size_t& bit, const bool& value) | |
| { | |
| if(value) | |
| { | |
| enableBit(input, bit); | |
| } else { | |
| disableBit(input, bit); | |
| } | |
| return input; | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment