将字节转换为二进制字符串的简单方法是什么? [英] Whats a simple way to turn bytes into a binary string?

查看:97
本文介绍了将字节转换为二进制字符串的简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文件中的字节转换为1和0的字符串,

I need to turn bytes from a file into a string of 1's and 0's,

file = open("Some_File.jpg","rb")
data = file.read()
file.close()
binary = some_function(data)
print(binary)
>>> 0100101000010101001...

我已经设法通过先将字节转换为Base64来获得等效的内容,但是这会使字符串的长度非常长.我看过的其他问题是关于将二进制字符串转换为个字节,但我找不到相反的地方.

I've managed to get something equivalent by converting the bytes into Base64 first, however this makes the size of the string very long. Other questions I have looked at are about turning binary strings into bytes, but I can't find any of the opposite.

此问题被标记为与另一个问题重复,但是该问题正在将字符串转换为二进制.如果我想这样做,我只是将其转换为Base64,但是它太长了.我需要一种将字节直接"1"和"0"的字符串的方法

This question was marked as a duplicate of another question, however this question is turning a string into binary. If I wanted to do that, I would just convert it into Base64, however it makes it far too long. I need a way to to 'bytes' directly into a string of 1's and 0's

推荐答案

基于评论中的讨论,我不认为您要问的是您实际上想做什么.但是,假设您要将python字节字符串转换为文字的零和一的字符串,这是一种实现方法:

Based on the discussion in the comments, I am not convinced that what you ask about is what you actually want to do. However assuming you want to convert a python bytestring to a string of literal zeros and ones, here's one way to do it:

import itertools

def bytes_to_bits(bytes_to_print: bytes):
    bits = [
        ["1" if byte & 2 ** i else "0" for i in range(7, -1, -1)]
        for byte in bytes_to_print
    ]
    return ''.join(itertools.chain.from_iterable(bits))


if __name__ == "__main__":
    print(bytes_to_bits(b"ABC"))

这篇关于将字节转换为二进制字符串的简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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