0

I have a binary matrix which I create by NumPy. The matrix has 6 rows and 8 columns.

array([[1, 0, 1, 1, 1, 0, 1, 1],
       [1, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 1, 0, 0, 1, 1, 1],
       [1, 0, 1, 1, 0, 1, 1, 0],
       [0, 1, 0, 0, 1, 0, 1, 1],
       [0, 1, 0, 1, 1, 1, 0, 0]])

First column is the sign of a number.

Example:

1, 0, 1, 1, 1, 0, 1, 1 -> 1 0111011 -> -59

When I used int(str, base=2) as a result I received value 187, and the value should be -59.

>>> int(''.join(map(str, array[0])), 2)
>>> 187

How can I convert the string into the signed integer?

3 Answers 3

2

Pyhton doesn't know that the first bit is supposed to represent the sign (compare with bin(-59)), so you have to handle that yourself, for example, if A contains the array:

num = int(''.join(map(str, A[0,1:])), 2)
if A[0,0]:
    num *= -1

Here's a more Numpy-ish way to do it, for the whole array at once:

num = np.packbits(A).astype(np.int8)
num[num<0] = -128 - num[num<0]

Finally, a code-golf version:

(A[:,:0:-1]<<range(7)).sum(1)*(1-2*A[:,0])
Sign up to request clarification or add additional context in comments.

Comments

0

You could split each row a sign and value variable. Then if sign is negative multiply the value by -1.

row = array[0]
sign, value = row[0], row[1:]
int(''.join(map(str, value)), 2) if sign == 0 else int(''.join(map(str, value)), 2) * -1

Comments

0

First of all, it looks like NumPy array rather than NumPy matrix. There are a couple options I can think of. Pretty straight forward way will look like that:

def rowToSignedDec(arr, row):
    res = int(''.join(str(x) for x in arr[row][1:].tolist()),2)

    if arr[row][0] == 1:
        return -res

    else:
        return res

print rowToSignedDec(arr, 0)

-59

That one is clearly not the most efficient one and neither the shortest one-liner:

int(''.join(str(x) for x in arr[0][1:].tolist()),2) - 2*int(arr[0][0])*int(''.join(str(x) for x in arr[0][1:].tolist()),2)

Where arr is the above-mentioned array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.