Here is a solution with structs since I do not know how python represents negative numbers binarily.
import struct
struct.unpack('H', struct.pack('h', number))
It packs it as a short (2 bytes) and unpacks it as an unsigned short.
Answer from User on Stack OverflowHere is a solution with structs since I do not know how python represents negative numbers binarily.
import struct
struct.unpack('H', struct.pack('h', number))
It packs it as a short (2 bytes) and unpacks it as an unsigned short.
>>> import numpy as np
>>> np.array([-20357],dtype="uint16")
array([45179], dtype=uint16)
in your case when you are done looping over everything and you have it in a list
just call np.array(my_list,dtype="uint16")
SOLVED: 3 Solutions:
-
using Numpy : np.uint16()
-
Using CTypes : ctypes.c_uint16()
-
Using Bitwise : & 0xFFFF
Hi, I'm trying to convert this code to Python from Go / C. It involves declaring a UInt16 variable and run a bit shift operation. However cant seem to create a variable with this specific type. Need some advise here.
Go Code:
package main
import "fmt"
func main() {
var dx uint16 = 38629
var dy uint16 = dx << 8
fmt.Println(dy) //58624 -> Correct value
}
Python Code:
dx = 38629 dy = (dx << 8) print(dy) # 9889024 -> not the expected value print(type(dx)) # <class 'int'> print(type(dy)) # <class 'int'>
I cant seem to figure out a way to cast or similar function to get this into an Unsigned Int 16.\
Please help.
Receiving 16-bit integers in Python - Stack Overflow
c# - How to convert from string to 16-bit unsigned integer in python? - Stack Overflow
Python Unsigned 16-bit Integer Array Elements - Stack Overflow
Converting integer to 16-bit hexadecimal in Big-endain form
Check out hex() and, more importantly struct:
http://docs.python.org/2/library/struct.html
This lets you convert a decimal into binary data. I've used it to read binary files, so it might be what you are looking for. I'm weak on theory so I tend to just bang on stuff until I get it right, but I would start with:
>>> import struct
>>> struct.pack('>h', -200)
b'\xff8'And see what the machine makes of it, and adjust accordingly.
More on reddit.comI'm trying to take a number (such as -200) and send it to a robot. The number must be converted to big-endian and sent in two bytes. WolframAlpha does this (the result I need to send is 38ff) but I haven't found a way to do this in python.
Check out hex() and, more importantly struct:
http://docs.python.org/2/library/struct.html
This lets you convert a decimal into binary data. I've used it to read binary files, so it might be what you are looking for. I'm weak on theory so I tend to just bang on stuff until I get it right, but I would start with:
>>> import struct
>>> struct.pack('>h', -200)
b'\xff8'
And see what the machine makes of it, and adjust accordingly.
u/1328 was close with struct, the code you are looking for is:
import struct
print struct.pack('>i', your_int)
>I is the indicator for Big Endian as according to struct.
Python Struct Documentation
EDIT: I just tested this code, and got the same result as u/1328. I'm looking into this more.
EDIT 2: OK. Wolfram's representation of the number -200 in hexadecimal is as an unsigned 16 bit integer. THey make a note that this number overflowed, and the reason is that -200 is, inherently, a signed number.
Are you sure you need to send the number is ff38, and not xff8?
If so, then you need to do some hackery to get this working. Something like:
import struct
def toBigEndian(number):
if number < 0:
number = 65536 + number
return struct.pack('>i',number)
I have a 32 bit number A = A3A2A1A0 that has been given to me in the form of A = B1B0 where B1 = A3A2 and B0 = A1A0. B1 and B0 are each 16 bit numbers. I now want to use B1 and B0 to get A in an unsigned integer format.
I tried using the 2's complement representation of B1 and B0 but am still not clear as to how I would "add" those two binary numbers.
I also tried using the bin(integer) function in Python to get the binary representation of both B1 and B0 in a list format and then concatenated the two lists to give me A. However, that didn't seem to work if either of B1 or B0 were negative.
I'm not quite understanding how B1 is getting affected when B0 goes into the overflow, i.e crosses 32768 to give a negative number.
If anyone could give me few examples taking B1 and B0 to be positive and negative both, with the final answer A as well that would be great. Any hints and suggestions would be appreciated. Thank you.
If your input is [0x20, 0x00], then you can do (arr[1]<<8)|arr[0].
If your input is ["0x20", "0x00"], then you can do int(arr[1],16)<<8)|int(arr[0],16).
This also works:
>>> import struct
>>> struct.unpack('<H', ''.join(map(chr, [0x20, 0x00])))[0]
32
The struct module is quite generic, it can be used in similar situations, and it becomes convenient as soon as 4-byte or 8-byte integers are needed.
(using python 3 here, there are some nomenclature differences in 2)
Well first, you could just leave everything as bytes. This is perfectly valid:
reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)
bytes allows for "tuple unpacking" (not related to struct.unpack, tuple unpacking is used all over python). And bytes is an array of bytes, which can be accessed via index as you wanted.
b = struct.pack('<H',0xABCD)
b[0],b[1]
Out[52]: (205, 171)
If you truly wanted to get it into an array.array('B'), it's still rather easy:
ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])
print("0x%X" % ary[0])
# 0xCD
For non-complex numbers you can use divmod(a, b), which returns a tuple of the quotient and remainder of arguments.
The following example uses map() for demonstration purposes. In both examples we're simply telling divmod to return a tuple (a/b, a%b), where a=0xABCD and b=256.
>>> map(hex, divmod(0xABCD, 1<<8)) # Add a list() call here if your working with python 3.x
['0xab', '0xcd']
# Or if the bit shift notation is distrubing:
>>> map(hex, divmod(0xABCD, 256))
Or you can just place them in the array:
>>> arr = array.array('B')
>>> arr.extend(divmod(0xABCD, 256))
>>> arr
array('B', [171, 205])