• Please review our updated Terms and Rules here

Clamping and Modulo via Bitwise Functions as First Class Language Feature?

segaloco

Experienced Member
Joined
Apr 30, 2023
Messages
475
So I've been playing heavy with ways to express abstract operations through equates in disassemblies I've been working on, and have long had a practice of having bitmasks of contiguous bits either from the left or right of a byte or word to express modulo and clamp operations. For instance, (0b00001111 & x) is modulo 16 and (0b11110000 & x) is clamping a value to a multiple of 16.

Towards this end, I keep headers in various disassembly projects expressing these like MOD_16, CLAMP_16, MOD_8, CLAMP_32, etc. Obviously modulo exists in numerous programming languages as a distinct operation, but I can't say any languages I've worked with I've seen clamping as a first-class feature. Furthermore, combinations thereof likewise have to be expressed instead at the very least as a modulo combined with bitwise and, although this can be simplified by using a single bitwise-and featuring any series of contiguous bits (e.g. 0b00111000 and 0b01111100 qualify but 0b00101100 and 0b00000101 do not) expresses a modulo and clamp operation.

Have any languages featured the clamp as a first-class operation, especially in a way that could be easily combined with modulos and then optimized into bitwise-and operations of contiguous bits? This is a practice I've taken to lately in my own disassembly projects, constants like (MOD_64&CLAMP_16) to express things like 0b00110000.
 
To me, clamping is confining a variable to a given range (minimum <= variable <= maximum). What you call "clamp", I know as "align".

These are uncommon operations. I've mainly used them in low-level code for optimization purposes, where they live in very restricted areas. Enforcing a bitmask implementation (which limits them to powers of two) pushes them even more in that direction.

I do not see a need for any language to have them as first-class citizens, and I am not aware of any language which does. Both the C preprocessor and C++ templates provide almost-perfect solutions to the problem (and I am sure Rust has something equally powerful).

Personally, I find (MOD_64&CLAMP_16) harder to read than 0b00110000 or 0x30.
 
I eventually intend to change that into a macro that takes the values as numerical symbols. That would then allow using such numeric symbols as both operands and modulo/clamp values. That should make editing values to different powers of two pretty trivial.
 
Back
Top