在Python中将哈希字符串表示为二进制

2 投票
4 回答
6998 浏览
提问于 2025-04-30 23:32

考虑一下下面这张图片:

在这里输入图片描述

我该如何把哈希码表示成二进制格式(比如 0110011)呢?

谢谢!

暂无标签

4 个回答

0

稍微晚了一点,但可以试试这个:

binhashcode = ''.join(bin(int(i,16)).zfill(4) for i in hashcode)
0

你可以使用 bin() 这个函数。

bin(d077ff) # Result: '0b11...'

如果你想去掉前面的 0b,可以这样做:

int(str(temp)[2:])
4
>>> import hashlib
>>> s="cat"
>>> hashcode=hashlib.md5(s).hexdigest()
>>> bin(int(hashcode,16))
'0b11010000011101111111001001000100110111101111100010100111000011100101111010100111010110001011110110000011010100101111110011011000'

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

2

试试这个:

最初由 @Ashwini Chaudhary 回答

''.join(format(ord(n),'b') for n in hashcode)
'11001001100001101111101111100110110010110100110100110010011001011100110111000110000111011111000011001011101011100101110000111011111010111100011000101100100111000110011110101110010110011011000111100100111000'

另一个更新

这是 @m.wasowski 提出的更简洁的方法,我正在结合他的想法来尝试解决这个问题(我仍然不确定这是否正是提问者想要的,因为句子中单词的长度并不一致):

def text_to_bin(text, n_bin=16):
    if n_bin < 16 or n_bin > 36:
        print "n_bin must be >= 16 and <= 36"
    else:
        for word in text.split():
            word_ord = ['{}'.format(bin(int(hashlib.md5(word).hexdigest(), n_bin)))]
            print '{} {}'.format(word, ''.join(word_ord)[2:])

text_to_bin('A cat in the woods', 16)
A 1111111110001010110001001110000111001111010011100001111101010000001101001011001001101011011011100101110101011001011111000101001
cat 11010000011101111111001001000100110111101111100010100111000011100101111010100111010110001011110110000011010100101111110011011000
in 10011101101011011111111101001011011110011111000101111111001000001000111001001111101100110111101001010010110000010101011011111
the 10001111110001000010110001101101110111111001100101100110110110110011101100001001111010000100001101100101000000110100001101010111
woods 10110111101111111011100101001001001001111100010000000101011101111100000100000001100111100000000010000100110101110011001010010111

撰写回答