在Python中将整数数组转换为二进制数组 [英] Converting integer array to binary array in python

查看:1463
本文介绍了在Python中将整数数组转换为二进制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python 2.7将具有整数的数组转换为二进制.

I am trying to convert an array with integers to binary, using python 2.7.

我的代码的简化版本如下:

A simplified version of my code is the following:

 #!/usr/bin/python
 import numpy as np

 a=np.array([6,1,5,0,2])
 b=np.array(np.zeros((5)))

for i in range(10):
    b[i]=bin(int(a[i])).zfill(8)

代码给我错误消息:

b [i] = bin(int(a [i])).zfill(8) ValueError:无效的float()文字:0000b110

b[i]=bin(int(a[i])).zfill(8) ValueError: invalid literal for float(): 0000b110

我的代码有什么问题? 还有另一种方法吗? 原始代码是一个更大的二维数组项目的一部分.

What is wrong with my code? Is there another way to do this? The original code is part of a much greater project with 2 dimensional arrays.

p.s我是Python的相对新手

p.s I'm a relative novice to Python

推荐答案

Numpy尝试将您的二进制数字转换为float,不同之处在于您的数字包含无法解释的b;此字符是通过bin函数添加的,例如. bin(2)0b10.您应该像这样在zfill之前删除此b字符,方法是使用切片"来删除前2个字符:

Numpy attempts to convert your binary number to a float, except that your number contains a b which can't be interpreted; this character was added by the bin function, eg. bin(2) is 0b10. You should remove this b character before your zfill like this by using a "slice" to remove the first 2 characters:

b[i]=bin(int(a[i]))[2:].zfill(8)

这篇关于在Python中将整数数组转换为二进制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆