Skip to content

Instantly share code, notes, and snippets.

@jaeoh2
Created March 6, 2019 02:27
Show Gist options
  • Save jaeoh2/3ab40ee710fb506a50109e3b1299154a to your computer and use it in GitHub Desktop.
Save jaeoh2/3ab40ee710fb506a50109e3b1299154a to your computer and use it in GitHub Desktop.
Two's complement Upscaler
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