How to modify bits in an integer?

前端 未结 4 2272
暖寄归人
暖寄归人 2020-12-08 21:01

I have an integer with a value 7 (0b00000111) And I would like to replace it with a function to 13 (0b00001101). What is

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 21:37

    You can use bitwise opertions. http://wiki.python.org/moin/BitwiseOperators

    if you want to set a given bit to 1 you can use bitwise 'or' with 1 on given position:

    0b00000111 | 0b00001000 = 0b00001111

    to set a given bit to 0 you can use bitwise 'and'

    0b00001111 & 0b11111011 = 0b00001011

    Note that 0b prefix is for binary numbers and 0x is for hexadecimal.

提交回复
热议问题