How do I enable Ctrl-A and Ctrl-X to increment and decrement binary numbers like 0b1010 in Vim?
Answer
:set nrformats+=bin
Explanation
Vim's <C-a> and <C-x> commands increment and decrement numbers under the cursor, but by default they only handle decimal and hexadecimal. Adding bin to nrformats extends this to binary numbers in the 0b... prefix format, making it easy to work with binary literals in code.
How it works
nrformatscontrols which number formats Vim recognizes for<C-a>and<C-x>- Default value includes
hex(0x...) and sometimesoctal(leading zero) - Adding
binenables recognition of binary numbers with the0bprefix +=appends to the option without removing existing values
Example
With :set nrformats+=bin active, place your cursor on the number in:
const MASK = 0b00001111;
Pressing <C-a> increments it to:
const MASK = 0b00010000;
And <C-x> decrements it back. Vim correctly carries bits across digit boundaries.
Tips
- Add
:set nrformats+=binto yourvimrcto make it permanent - Combined with visual block mode and
g<C-a>, you can create incrementing binary sequences - To remove octal interpretation (which treats
007as octal), use:set nrformats-=octal - Check current value with
:set nrformats? - Works with
<C-a>in normal mode and also via Ex::%s/0b\([01]\+\)/\=0b.../for bulk changes