unsigned mask = k ? ((1 << (8 * sizeof(int)-k)) - 1) : 0;
I think this cannot be what you wanted. Example (k==1): mask = 0x7FFFFFFF
Then you use "mask | xsrl" which gives "0x7FFFFFFF" (it's an OR operation...)
Just thinking aloud: I think you might want
unsigned mask = k ? (0xFFFFFFFF<<(32-k)) : 0;
To be really precise:
unsigned int mask = 0;
if ( k > 0 && k <= (8*sizeof(int)))
mask = UINT_MAX<<((8*sizeof(int))-k);
and you need to include "limits.h" to get "UINT_MAX".