Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

python - Get and Set specific bits of a value

For a given value, I need to be able to read and write to specific bits of said value.

Example :

n = 341
# bin(341) is '0b101010101'

get_bits(n, start = 2, end = 6)
# Returns 10 = '0b1010'

n = set_bits(n, start = 2, end = 6, newValue = 6)
# Replaces bits [2:6] of n with 0b0110
# Makes n = 309 = '0b100110101'
question from:https://stackoverflow.com/questions/66045290/get-and-set-specific-bits-of-a-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Normally bits are numbered from right to left. If you used that standard convention and a start-stop value (like a range), your functions would be simpler to implement with bitwise operators:

def get_bits(n, start, end):
    return (n&((1<<end)-1))>>start

def set_bits(n, start, end, value):
    mask = (1<<end) - (1<<start) 
    return (n&~mask) | (value<<start)&mask

output:

n = 341  # 101010101
         # 876543210 bit numbers

                           # 101010101 = 341 
f"{get_bits(n,3,7):b}"     # ..1010... = 10
                           # 876543210

                           # 101010101 = 341 
f"{set_bits(n,3,7,12):b}"  # 101100101 = 357
                           # ..^^^^...
                           # ..1100... = 12
                           # 876543210

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...