[英]Convert a decimal number into a byte size of 8 bit array
x = 64
var_in_bin_format = bin(64)
print(var_in_bin_format)
#Output
#0b1000000
#Desired Output -- > should always be in 8 bit format
#0b01000000
def call_another_api(var_in_bin_format):
pass
In Python, I need to call an API that expects its parameter to be always in 8 bit format regardless of the value of the decimal number?在 Python 中,我需要调用一个 API,无论十进制数的值如何,它都希望其参数始终为 8 位格式?
I am not that good in bit manipulation so I am thinking if there is something I can do here?我在位操作方面不是那么好,所以我在想是否有什么我可以在这里做的?
How can I do this?我怎样才能做到这一点? I cannot use the format() function as it will convert the value into a string representation and the API that I am calling will alert me that it is not in the correct format.我不能使用 format() function 因为它会将值转换为字符串表示形式,并且我正在调用的 API 会提醒我它的格式不正确。
Even though you say that you can't use format()
because it returns a string, I'm going to post this because that's also what bin()
does.即使你说你不能使用format()
因为它返回一个字符串,我还是要发布这个,因为这也是bin()
所做的。 bin(x)
is equivalent to format(x, '#b')
. bin(x)
等价于format(x, '#b')
。 I'd guess that you haven't added the '#'
, which means you won't have '0b'
leading the value.我猜你没有添加'#'
,这意味着你不会有'0b'
领先的价值。
The Python 3 documentation for bin()
actually gives a pretty strong hint about how you might do this, using format
instead. bin()
的Python 3 文档实际上给出了关于如何执行此操作的非常强烈的提示,而是使用format
。
If you know that the value passed will not be negative, you can use the format string '#010b'
:如果您知道传递的值不会为负,则可以使用格式字符串'#010b'
:
format(x, '#010b')
Breaking this down:打破这个:
'b'
means that the number will be a string binary representation. 'b'
表示该数字将是一个字符串二进制表示。'10'
means that the entire string will be 10 characters long, two for '0b' and 8 for the value. '10'
表示整个字符串的长度为 10 个字符,两个用于 '0b',8 个用于值。'0'
makes it pad with '0'
instead of ' '
. '0'
使它用'0'
而不是' '
填充。'#'
will add the '0b'
prefix, as done by bin()
. '#'
将添加'0b'
前缀,正如bin()
所做的那样。 Note that this assumes that the number is an integer in the range [0, 255].请注意,这假定数字是 [0, 255] 范围内的 integer。 Integers outside this range will generate valid representations, but will not match the format expected, and may have a leading '-'
.此范围之外的整数将生成有效的表示,但与预期的格式不匹配,并且可能有一个前导'-'
。 Objects of type float
can not be converted with the 'b'
format code. float
类型的对象不能用'b'
格式代码转换。 I assume that these are not problems, given what your intended output is, but it might be a good idea to add an explicit check to throw a ValueError
if the value is less than 0 or greater than 255.考虑到您的预期 output 是什么,我认为这些都不是问题,但是如果值小于 0 或大于 255,添加显式检查以抛出ValueError
可能是个好主意。
If you're in Python 3.6+, you could also use f-strings:如果您使用的是 Python 3.6+,您还可以使用 f 字符串:
f'{x:#010b}'
Is is not possible to convert all decimal numbers to 8 bit.不可能将所有十进制数转换为 8 位。 You can only convert numbers from 0 to 255 in 8 bits.您只能将 0 到 255 的数字转换为 8 位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.