Created
July 18, 2015 04:38
-
-
Save jhaberstro/023fe5680ce391064823 to your computer and use it in GitHub Desktop.
Nifty sign extend
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< unsigned SrcSize, unsigned DstSize > | |
static inline uint32_t signExtend(uint32_t x) | |
{ | |
static_assert(SrcSize <= 32, "SrcSize cannot be larger than 32 bits."); | |
static_assert(SrcSize <= 32, "DstSize cannot be larger than 32 bits."); | |
static_assert(SrcSize < DstSize, "DstSize must be larger than SrcSize."); | |
constexpr unsigned src_mask = (1 << SrcSize) - 1; | |
constexpr unsigned extension = ((1 << (DstSize - SrcSize)) - 1) << SrcSize; | |
uint32_t result = x & src_mask; | |
uint32_t is_signed = (x & (1 << (SrcSize - 1))) >> (SrcSize - 1); | |
result |= (extension * is_signed); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment