Skip to content

Instantly share code, notes, and snippets.

@jhaberstro
Created July 18, 2015 04:38
Show Gist options
  • Save jhaberstro/023fe5680ce391064823 to your computer and use it in GitHub Desktop.
Save jhaberstro/023fe5680ce391064823 to your computer and use it in GitHub Desktop.
Nifty sign extend
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