Skip to content

Instantly share code, notes, and snippets.

@spot62
Created April 23, 2019 08:40
Show Gist options
  • Save spot62/30d9ffc23a2993ea301072fbcabf9fb2 to your computer and use it in GitHub Desktop.
Save spot62/30d9ffc23a2993ea301072fbcabf9fb2 to your computer and use it in GitHub Desktop.
Byte clamp
static unsigned char byte_clamp(int c)
{
unsigned char rc = { static_cast<unsigned char>(c), 255, 0 };
unsigned uc = static_cast<unsigned>(c);
// +1 if greater 255
// and +1 if bit of sign 1
return rc[!!(uc & ~0xff) + !!(uc & ~(~0u >> 1))];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment