简体   繁体   English

如何在python中知道二进制字符串或ascii字符串

[英]How to know binary string or ascii string in python

I have a string variable for mac address. 我有一个用于Mac地址的字符串变量。 it can be binary - '\\x00\\x04\\x96\\x82Q\\xbb' or ascii - 'c8:be:19:c6:a0:e0'. 它可以是二进制-'\\ x00 \\ x04 \\ x96 \\ x82Q \\ xbb'或ascii-'c8:be:19:c6:a0:e0'。 If it is binary i need to convert it to ascii string with b2a_hex function. 如果是二进制文件,则需要使用b2a_hex函数将其转换为ascii字符串。 Is it possible to know what type of string i am having now? 是否可以知道我现在使用的是哪种类型的字符串?

hex(number) -> string 十六进制(数字)->字符串

Return the hexadecimal representation of an integer or long integer. 返回整数或长整数的十六进制表示形式。

//this function use to get decimal number and then using that decimal get hexadecimal number. //此函数用于获取十进制数,然后使用该十进制获取十六进制数。

>>int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>> 

>>> hex(int('0000010010001101', 2))
'0x48d'

Look at the length. 看长度。 If it's 6 then you have binary, if it's bigger then it's text. 如果是6,则表示二进制文件;如果大于6,则表示文本文件。

if len(s) <= 6:
    s = binascii.b2a_hex(s)

您也可以使用简单的find 。如果string.find(":") == -1 ,则为二进制,否则为ascii。

Mac address is 48 bits long. Mac地址为48位长。

If a Mac address is presented in binary, it will take 6 bytes.( 8bit(1Byte)*6=46bits) 如果Mac地址以二进制形式显示,则将占用6个字节。(8bit(1Byte)* 6 = 46bits)

If a Mac address is presented in ascii, it will take 17 ASCII characters (17 bites). 如果Mac地址以ascii形式显示,它将需要17个ASCII字符(17位)。

So, if the data is 6 bytes, it may contain Mac address in binary. 因此,如果数据为6个字节,则它可能包含二进制的Mac地址。 if the data is 17 bytes or more, it may contain Mac address in ASCII. 如果数据为17个字节或更多,则可能包含ASCII的Mac地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM