python bitwise operation - python

hi i am new in python just started learning with python i got a task in which i need to store "1" byte of integer into different bits just like RGB the value are store in that can any one would write a small program for me and explain that ,please i need a help
Thankyou

I'll assume this question is legitimate and appropriate for the forum..
# To Encode:
r = 1
g = 2
b = 3
rgb = r << 16 | g << 8 | b
#To extract:
r = (rgb >> 16) & 0xFF
g = (rgb >> 8) & 0xFF
b = rgb & 0xFF

To convert a number to a list of it's binary digits: list(bin(number))[2:]

Related

Convert strings to int using many operators

I had a string of int as a result of converting text to int. Here is its code in python:
def mix(data):
b = len(data)*8
m = bytes_to_long(data)
c = 0
for i in range(b//2):
if (m >> i) & 1:
c ^= m >> (b//2) << i
return c
So now, I had to make an "unmix" function to decode my result to its origin. But I'm still struggling with those Binary Shift Operators. Can you guys help me, please?

python reverse a binary pattern within an integer

Is there a fast possibility to reverse a binary number in python?
Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a fast function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for your effort.
Edit:
Performances. I tested the code for all 2^16 pattern several times.
winner are the partially look up tables: 30ms
2nd int(format(num, '016b')[::-1], 2) from the comments: 56ms
3rd x = ((x & 0x00FF) << 8) | (x >> 8): 65ms
I did not expect my approach to be so horribly slow but it is.
approx. 320ms. Small improvement by using + instead of | 300ms
bytes(str(num).encode('utf-8')) fought for the 2nd place but somehow
the code did not provide valid answers. Most likely because I made a
mistake by transforming them into an integer again.
thank you very much for your input. I was quite surprised.
This might be faster using small 8-bit lookup table:
num = 11
# One time creation of 8bit lookup
rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)]
# Run for each number to be flipped.
lower_rev = rev[num & 0xFF] << 8
upper_rev = rev[(num & 0xFF00) >> 8]
flipped = lower_rev + upper_rev
I think you can just use slicing to get what you are looking for:
b=bytes('0000000000001011'.encode('utf-8'))
>>> b
b'0000000000001011'
>>> b[::-1]
b'1101000000000000'
There's this, but in Python it seems slower than Matthias' proposed int->str->int solution.
x = ((x & 0x5555) << 1) | ((x & 0xAAAA) >> 1)
x = ((x & 0x3333) << 2) | ((x & 0xCCCC) >> 2)
x = ((x & 0x0F0F) << 4) | ((x & 0xF0F0) >> 4)
x = ((x & 0x00FF) << 8) | (x >> 8)
My current approach is to access the bits via bit shifting and mask and to shift them in the mirror number until they reach their destination. Still I have the feeling that there is room for improvement.
num = 11
print(format(num, '016b'))
right = num
left = 0
for i in range(16):
tmp = right & 1
left = (left << 1 ) | tmp
right = right >> 1
print(format(left, '016b'))

how to make 16bit to 8bit like that 0x0300 to 0x03 and 0x00 by python?

how to make 16bit to 8bit like that 0x0300 to 0x03 and 0x00 by python?
i try to it like that
reg = 0x0300
print(reg[0:4], reg[4::])..
it show me that 'int' object is not subscriptable
reg = 0x0316
regbinary = bin(reg)
print(regbinary)
regBotoom = regbinary[-8::]
print(regBotoom)
result = hex('0b'+regBotoom)
print(result)
it show me that
0b1100010110
00010110
TypeError: 'str' object cannot be interpreted as an integer
You can get lower and higher 8 bits with bitwise AND and shifting:
reg = 0x0316
lowBits = reg & 0xFF
highBits = (reg >> 8) & 0xFF
print(lowBits)
print(highBits)
Bitwise Operators:
x = 0x4321
y = x >> 8
= 0x43
z = x & 0x00ff
= 0x21
You can not manipulate an int like you are trying to do without converting it to a string first.
Perhaps you're after the answer #jafarlihi gave, where reg is really just an int and you shift its value to get the values you're after.
However, you may also want to see this:
import struct
reg = 790
regb = struct.pack('h', reg)
print(regb)
msb, lsb = struct.unpack('bb', regb)
print(msb, lsb)
regb_2 = struct.pack('bb', msb, lsb)
print(regb, regb_2)
value = struct.unpack('h', regb)
print(reg, value)
Result:
b'\x16\x03'
22 3
b'\x16\x03' b'\x16\x03'
790 (790,)
reg = 0x0300
print(hex((reg >> 8) & 0xFF))
print(hex(reg & 0xFF))
Output :
0x3
0x0

How I do circular shifting (rotation) of int in Python?

In Java right rotation is done using:
(bits >>> k) | (bits << (Integer.SIZE - k))
But how to do similar thing in Python?
I tried to do (as described here):
n = 13
d = 2
INT_BITS = 4
print(bin(n))
print(bin((n >> d)|(n << (INT_BITS - d)) & 0xFFFFFFFF))
Output:
0b1101
0b110111
But I could not interpret this as a right rotation.
Also is it possible to perform the rotation by excluding leading zeroes, for example:
rightRotation of (...0001101) = 1110 not 1000...110
It is my mistake, if you want to change INT_BITS to 4 you also need to change 0xFFFFFFFF to 0xF (one hex equals 4-bits):
n = 13
d = 2
INT_BITS = 4
print(bin(n))
print(bin((n >> d)|(n << (INT_BITS - d)) & 0xF))
will output:
0b1101
0b111

Why is there bit shifting when converting to an image from an array?

I'm trying to create a QPixmap from a numpy array. The numpy array image is going to be 2D (ie no color info just grayscale).
I'm trying to adapt this answer to my needs however I don't quite understand this line:
b = (255 << 24 | a[:,:,0] << 16 | a[:,:,1] << 8 | a[:,:,2]).flatten() # pack RGB values
There is some bitshifting going on and some bitwise or' ing but I don't quite get it to be honest.
So my dumbed down example is as follows:
x, y = np.meshgrid(np.arange(1920), np.arange(1080), indexing='ij'); z = np.sin(0.03*x)*np.cos(0.005*y)
imgPNFN = z
if imgPNFN.ndim == 2:
imgPNFN = imgPNFN[:,:,np.newaxis].repeat(3, 2)
imMin = np.min(imgPNFN)
imDelta = np.max(imgPNFN) - np.min(imgPNFN)
im1 = ((imgPNFN-imMin)/imDelta*255).astype(np.uint32)+1 #<-- had to add 1 for some reason otherwise got weird results...
im2 = 255 << 24 | im1[:,:,0] << 16 | im1[:,:,1] << 8 | im1[:,:,2]
im3 = QtGui.QImage(im2, im2.shape[1], im2.shape[0], QtGui.QImage.Format_RGB32)
which seems to work but when my image is lena ie:
from scipy.misc import lena
l = sp.misc.lena()
imgPNFN = l
#etc...
It doesn't work... I think it's because of my lack of understanding of what the bitshifting is doing... Also, if there is a better way to do the RGB (ie I'm copying things over to pretend I have the same values) if I could avoid that somehow that would be great.
Thanks in advance!
I assume that you want to know why the bit-shifting and or-ing is happening. Well, you need to join the A[lpha], R[ed], G[reen], and B[lue] bytes together to form a single integer value. Pixel data is a 2D array of integer; scalar value. They are not tuples of bytes.
Example
Color: Periwinkle
A: 255 -> 11111111
R: 204 -> 11001100
G: 204 -> 11001100
B: 255 -> 11111111
Formula
Value = A << 24 | R << 16 | G << 8 | B
Bit-Math
11111111000000000000000000000000
110011000000000000000000
1100110000000000
+ 11111111
---------------------------------
11111111110011001100110011111111
Base conversion
111111111100110011001100111111112 = 429161190310
Finally
Based on the bit manipulation above, the color Periwinkle, with 100% opacity in ARGB, has a pixel value of 4,291,611,903.

Categories