Skip to content

Instantly share code, notes, and snippets.

@buszk
Created July 31, 2020 17:37
Show Gist options
  • Save buszk/08fdb1ad8ca6c08ca8e9260f3d00bc19 to your computer and use it in GitHub Desktop.
Save buszk/08fdb1ad8ca6c08ca8e9260f3d00bc19 to your computer and use it in GitHub Desktop.
Signed integer extension with number of bytes
int64_t signext(uint64_t val, uint64_t bytes) {
uint64_t bits = 8 * bytes;
uint64_t bitmask = (1 << bits) - 1;
uint64_t value = bitmask & val;
uint64_t mask = 1 << (bits-1);
if (mask & val) {
value |= ((uint64_t)-1) ^ bitmask;
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment