Created
March 6, 2019 02:27
-
-
Save jaeoh2/3ab40ee710fb506a50109e3b1299154a to your computer and use it in GitHub Desktop.
Two's complement Upscaler
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
template <typename Target, size_t Length> | |
// https://www.codeproject.com/Tips/1079637/Twos-Complement-for-Unusual-Integer-Sizes | |
class TwosComplementUpscaler | |
{ | |
Target bitfield : Length; | |
TwosComplementUpscaler(Target value) : bitfield(value){} | |
TwosComplementUpscaler(); | |
public: | |
static Target Convert(Target value) | |
{ | |
static_assert(sizeof(Target) * 8 > Length, "Length too large"); | |
static_assert(Length > 1, "Length too short"); | |
Target mask = (~0) << Length; | |
TwosComplementUpscaler temp(value & ~mask); | |
return static_cast<Target>(temp.bitfield); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment