I need to bit shift x by b, where b can be positive (shift left), zero (nop), or negative (shift right).
C bit shift doesn't handle negative shifts.
Can I define an inline func or macro to do this? Ideally, I wouldn't need to know the type of x when I write this - the macro (or inline func?) should support any integral type.
As noted in comments 1 and 2 to Barmar's answer:
You could use an inline function to avoid multiple evaluations of arguments:
Choose the parameter types to suit your needs — but the shift amount could be as small as
int8_tand not run into range problems in the foreseeable future.Note that shifting signed types has ramifications. The C11 standard §6.5.7 Bitwise shift operators sets the rules:
SRobertJames said:
And I responded:
You could use a macro to write these functions:
Note that there's no semicolon at the end of the macro invocations. If one were present, it would introduce an empty declaration at the top level.
Now you can use these functions just like any other, and the argument to the functions is evaluated once, avoiding concerns raised about multiple evaluations when a macro is used instead of an inline function.
It would be feasible to have the functions check that the shift amount is in the range -(size-1) .. +(size-1) — aborting if the value is out of range. This might be a 'debug' or 'development' mode option — you can make things more complicated if that suits your needs.