Zet hex om naar binair

Ik heb ABC123EFFF.

Ik wil 001010101111000001001000111110111111111111 hebben (d.w.z. binaire repr. met bijvoorbeeld 42 cijfers en voorloopnullen).

Hoe?


Antwoord 1, autoriteit 100%

Voor het oplossen van het probleem met de volgnul aan de linkerkant:


my_hexdata = "1a"
scale = 16 ## equals to hexadecimal
num_of_bits = 8
bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

Het geeft 00011010 in plaats van de getrimde versie.


Antwoord 2, autoriteit 56%

import binascii
binary_string = binascii.unhexlify(hex_string)

Lees

binascii.unhexlify

Retourneer de binaire gegevens die worden vertegenwoordigd door de hexadecimale tekenreeks die is opgegeven als de parameter.


Antwoord 3, autoriteit 44%

bin(int("abc123efff", 16))[2:]

Antwoord 4, autoriteit 26%

>>> bin( 0xABC123EFFF )

‘0b10101011111000001001000111110111111111111’


Antwoord 5, autoriteit 12%

"{0:020b}".format(int('ABC123EFFF', 16))

6, Autoriteit 8%

Hier is een tamelijk onbewerkte manier om het te doen met behulp van een beetje fulldling om de binaire snaren te genereren.

Het sleutelbit om te begrijpen is:

(n & (1 << i)) and 1

die een 0 of 1 genereren als het I’-bit van n is ingesteld.


import binascii
def byte_to_binary(n):
    return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))
def hex_to_binary(h):
    return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))
print hex_to_binary('abc123efff')
>>> 1010101111000001001000111110111111111111

EDIT: met behulp van de “nieuwe” Ternary-operator dit:

(n & (1 << i)) and 1

zou worden:

1 if n & (1 << i) or 0

(Welke tbh weet ik niet zeker hoe leesbaar is)


7, Autoriteit 4%

Dit is een lichte aanraking naar de oplossing van Glen Maynard, waarvan ik denk dat het de juiste manier is om het te doen. Het voegt gewoon het vulling-element toe.


    def hextobin(self, hexval):
        '''
        Takes a string representation of hex data with
        arbitrary length and converts to string representation
        of binary.  Includes padding 0s
        '''
        thelen = len(hexval)*4
        binval = bin(int(hexval, 16))[2:]
        while ((len(binval)) < thelen):
            binval = '0' + binval
        return binval

trok het uit een klas. Haal gewoon op self, als u in een stand-aleens script werkt.


8, Autoriteit 2%

Vervang elk HEX-cijfer met de overeenkomstige 4 binaire cijfers:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111

9, Autoriteit 2%

HEX – & GT; Decimal dan decimaal – & GT; Binair

#decimal to binary 
def d2b(n):
    bStr = ''
    if n < 0: raise ValueError, "must be a positive integer"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1    
    return bStr
#hex to binary
def h2b(hex):
    return d2b(int(hex,16))

10, Autoriteit 2%

Ik heb de berekening voor het aantal bits toegevoegd om te vullen tot de oplossing van Onedinkenedi. Hier is de resulterende functie:

def hextobin(h):
  return bin(int(h, 16))[2:].zfill(len(h) * 4)

Waarbij 16 het grondtal is waaruit je converteert (hexadecimaal), en 4 het aantal bits is dat je nodig hebt om elk cijfer weer te geven, of grondtal 2 van de schaal te loggen.


Antwoord 11

Een andere manier:

import math
def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
        idx -= 1
        if s % 2 == 1: digit_lst[idx] = '1'
        s = s / 2
    return ''.join(digit_lst)
print hextobinary('abc123efff')

Antwoord 12

# Python Program - Convert Hexadecimal to Binary
hexdec = input("Enter Hexadecimal string: ")
print(hexdec," in Binary = ", end="")    # end is by default "\n" which prints a new line
for _hex in hexdec:
    dec = int(_hex, 16)    # 16 means base-16 wich is hexadecimal
    print(bin(dec)[2:].rjust(4,"0"), end="")    # the [2:] skips 0b, and the 

Antwoord 13

Gebruik gewoon de module coden(opmerking: ik ben de auteur van de module )

Je kunt daar haxedecimaal naar binair converteren.

  1. Installeer met pip
pip install coden
  1. Converteren
a_hexadecimal_number = "f1ff"
binary_output = coden.hex_to_bin(a_hexadecimal_number)

De converterende zoekwoorden zijn:

  • hexvoor hexadeimal
  • binvoor binair
  • intvoor decimaal
  • _to_– het conversiesleutelwoord voor de functie

Je kunt dus ook formatteren:
e. hexadecimal_output = bin_to_hex(a_binary_number)


Antwoord 14

HEX_TO_BINARY_CONVERSION_TABLE = {
                              '0': '0000',
                              '1': '0001',
                              '2': '0010',
                              '3': '0011',
                              '4': '0100',
                              '5': '0101',
                              '6': '0110',
                              '7': '0111',
                              '8': '1000',
                              '9': '1001',
                              'a': '1010',
                              'b': '1011',
                              'c': '1100',
                              'd': '1101',
                              'e': '1110',
                              'f': '1111'}
def hex_to_binary(hex_string):
    binary_string = ""
    for character in hex_string:
        binary_string += HEX_TO_BINARY_CONVERSION_TABLE[character]
    return binary_string

wanneer ik hex_to_binary("123ade")

 %timeit hex_to_binary("123ade")

hier is het resultaat:

316 ns ± 2.52 ns per loop

U kunt ook de “join”-methode gebruiken:

def hex_to_binary_join(hex_string):
    hex_array=[]
    for character in hex_string:
        hex_array.append(HEX_TO_BINARY_CONVERSION_TABLE[character])
    return "".join(hex_array)

Ik heb dit ook getimed:

   %timeit hex_to_binary_join("123ade")
       397 ns ± 4.64 ns per loop 

Antwoord 15

def conversion():
    e=raw_input("enter hexadecimal no.:")
    e1=("a","b","c","d","e","f")
    e2=(10,11,12,13,14,15)
    e3=1
    e4=len(e)
    e5=()
    while e3<=e4:
        e5=e5+(e[e3-1],)
        e3=e3+1
    print e5
    e6=1
    e8=()
    while e6<=e4:
        e7=e5[e6-1]
        if e7=="A":
            e7=10
        if e7=="B":
            e7=11
        if e7=="C":
            e7=12
        if e7=="D":
            e7=13
        if e7=="E":
            e7=14
        if e7=="F":
            e7=15
        else:
            e7=int(e7)
        e8=e8+(e7,)
        e6=e6+1
    print e8
    e9=1
    e10=len(e8)
    e11=()
    while e9<=e10:
        e12=e8[e9-1]
        a1=e12
        a2=()
        a3=1 
        while a3<=1:
            a4=a1%2
            a2=a2+(a4,)
            a1=a1/2
            if a1<2:
                if a1==1:
                    a2=a2+(1,)
                if a1==0:
                    a2=a2+(0,)
                a3=a3+1
        a5=len(a2)
        a6=1
        a7=""
        a56=a5
        while a6<=a5:
            a7=a7+str(a2[a56-1])
            a6=a6+1
            a56=a56-1
        if a5<=3:
            if a5==1:
                a8="000"
                a7=a8+a7
            if a5==2:
                a8="00"
                a7=a8+a7
            if a5==3:
                a8="0"
                a7=a8+a7
        else:
            a7=a7
        print a7,
        e9=e9+1

Antwoord 16

ik heb een korte geknipte hoop dat helpt 🙂

input = 'ABC123EFFF'
for index, value in enumerate(input):
    print(value)
    print(bin(int(value,16)+16)[3:])
string = ''.join([bin(int(x,16)+16)[3:] for y,x in enumerate(input)])
print(string)

eerst gebruik ik uw invoer en som deze op om elk symbool te krijgen. dan converteer ik het naar binair en trim ik van de 3e positie tot het einde. De truc om de 0 te krijgen is om de maximale waarde van de invoer toe te voegen -> in dit geval altijd 16 🙂

de korte vorm is de join-methode. Geniet ervan.


Antwoord 17

De binaire versie van ABC123EFFF is eigenlijk 1010101111000001001000111110111111111111

Voor bijna alle toepassingen wilt u dat de binaire versie een lengte heeft die een veelvoud is van 4 met voorloopopvulling van nullen.

Om dit in Python te krijgen:

def hex_to_binary( hex_code ):
  bin_code = bin( hex_code )[2:]
  padding = (4-len(bin_code)%4)%4
  return '0'*padding + bin_code

Voorbeeld 1:

>>> hex_to_binary( 0xABC123EFFF )
'1010101111000001001000111110111111111111'

Voorbeeld 2:

>>> hex_to_binary( 0x7123 )
'0111000100100011'

Merk op dat dit ook werkt in Micropython 🙂


Antwoord 18

a = raw_input('hex number\n')
length = len(a)
ab = bin(int(a, 16))[2:]
while len(ab)<(length * 4):
    ab = '0' + ab
print ab

Antwoord 19

import binascii
hexa_input = input('Enter hex String to convert to Binary: ')
pad_bits=len(hexa_input)*4
Integer_output=int(hexa_input,16)
Binary_output= bin(Integer_output)[2:]. zfill(pad_bits)
print(Binary_output)
"""zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s
starting from right side but remaining 0 s will display till quantity x
[y:] where y is no of output chars which need to destroy starting from left"""

Antwoord 20

no=raw_input("Enter your number in hexa decimal :")
def convert(a):
    if a=="0":
        c="0000"
    elif a=="1":
        c="0001"
    elif a=="2":
        c="0010"
    elif a=="3":
        c="0011"
    elif a=="4":
        c="0100"
    elif a=="5":
        c="0101"
    elif a=="6":
        c="0110"
    elif a=="7":
        c="0111"
    elif a=="8":
        c="1000"
    elif a=="9":
        c="1001"
    elif a=="A":
        c="1010"
    elif a=="B":
        c="1011"
    elif a=="C":
        c="1100"
    elif a=="D":
        c="1101"
    elif a=="E":
        c="1110"
    elif a=="F":
        c="1111"
    else:
        c="invalid"
    return c
a=len(no)
b=0
l=""
while b<a:
    l=l+convert(no[b])
    b+=1
print l

Other episodes