.Convert String into a 2Bytearray(U32)- python
Question: I have a string `text="0000001011001100"` I want to convert this string into a
2 byte array something like this **(b'\x00\x02')**

    
    
    byte_array=(socket.htons(text)).to_bytes(2,sys.byteorder)
    

But this is not working and giving an error that **int** required I have
converted the text to **int** but then the entire string changes

I need help on this


Answer: You can convert text to integer and then you can use `struct` module

    
    
    import struct
    
    text = "0000001011001100"
    number = int(text, 2) # 716
    
    result = struct.pack("h", number)
    
    b'\xcc\x02'
    
    # or with > to change bytes order
    
    result = struct.pack(">h", number)
    
    b'\x02\xcc'
    

see: <https://docs.python.org/3/library/struct.html>

