Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Last active September 30, 2021 01:28
Show Gist options
  • Save jstaursky/9fa6ec26584c71f88eb24e1185509e92 to your computer and use it in GitHub Desktop.
Save jstaursky/9fa6ec26584c71f88eb24e1185509e92 to your computer and use it in GitHub Desktop.

C++ bit shifting and how it is reflected in memory.

The number

int16_t num =  0b1000_0000_0000_0001

stored as:

Little Endian.

                    LSB         MSB
lower addresses ... | 0000_0001 | 1000_0000 | ... upper addresses

becomes

LSB         MSB
| 0000_0010 | 0000_0000 |

(i.e.-- 0b0000_0000_0000_0010)

after test <<= 1


The number

int16_t num =  0b1000_0000_0000_0001

stored as:

Little Endian.

LSB         MSB
| 0000_0001 | 1000_0000 |

becomes

LSB         MSB
| 0000_0000 | 1110_0000 |

(i.e.-- 0b1110_0000_0000_0000)

after test >>= 2

because:

Right-shift on signed integral types is an arithmetic right shift, which performs sign-extension.

see c++20


Thus when testing bits with some_var & (1 << i)

i traverses some_var in the following order (in memory).

LSB         MSB
| 0000_0001 | 1000_0000 |
      <<                  (1)
                  <<      (2)

where

int16_t some_var =  0b1000_0000_0000_0001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment