PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How does python perform bitwise operations to store three values ​in an int?

 October 17, 2022     bit, bitwise-operators, integer, python, python-3.x     No comments   

Issue

For example, if I have an int with a length of 32 bits, how do I store value A in the first 16 bits, then store value B in bits 17-24, and value C in bits 25-32? And how can I get these three values ​​out of an int?


Solution

Assuming that your values fit in the assigned bit counts, it's just a question of shifting them to make an int, and then unshifting and masking to get them back:

A = 34945
B = 49
C = 233
B_shift = 16
C_shift = 24

result = A + (B << B_shift) + (C << C_shift)
print(result)

resA = result & ((1 << B_shift) - 1)
resB = (result >> B_shift) & ((1 << (C_shift - B_shift)) - 1)
resC = result >> C_shift

print(resA, resB, resC)


Answered By - Nick
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing