vimtricks.wiki Concise Vim tricks, one at a time.

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

  • nrformats controls which number formats Vim recognizes for <C-a> and <C-x>
  • Default value includes hex (0x...) and sometimes octal (leading zero)
  • Adding bin enables recognition of binary numbers with the 0b prefix
  • += 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+=bin to your vimrc to make it permanent
  • Combined with visual block mode and g<C-a>, you can create incrementing binary sequences
  • To remove octal interpretation (which treats 007 as 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

Next

How do I quit Vim without saving using a two-keystroke normal mode shortcut?