Ram
Ram

Reputation: 557

append 2 hex values in python

I am trying to append some hex values in python and I always seem to get 0x between the number. From what I searched, either this is not possible without converting it into a lit of values ?? I am not sure.

a = 0x7b
b = 0x80000
hex(a) + hex(b) = 0x7b0x80000

I dont want the 0x in the middle - I need, 0x7b80000. is there any other way to do this? If I convert to integer I get the sum of the two and converting it to hex is a different value than 0x7b80000

Upvotes: 9

Views: 38466

Answers (4)

You can use f-string formatting with Python 3:

>>> a = 0x7b
>>> b = 0x80000
>>> f'0x{a:x}{b:x}'
'0x7b80000'

Upvotes: 3

Algafix
Algafix

Reputation: 29

It's been 7 years but the accepted answer is wrong and this post still appears in the first place in google searches; so here is a correct answer:

import math

def append_hex(a, b):
 sizeof_b = 0

 # get size of b in bits
 while((b >> sizeof_b) > 0):
     sizeof_b += 1

 # every position in hex in represented by 4 bits
 sizeof_b_hex = math.ceil(sizeof_b/4) * 4


 return (a << sizeof_b_hex) | b

The accepted answer doesn't make sense (you can check it with values a=10, b=1a). In this solution, we search for the nearest divider of 4 - since every hex value is represented by 4 bits - and then move the first value this time of bits.

Upvotes: 2

Serdalis
Serdalis

Reputation: 10489

This is a more generic way to append hex / int / bin values.
Only works for positive values of b.

a = 0x7b
b = 0x80000

def append_hex(a, b):
    sizeof_b = 0

    # get size of b in bits
    while((b >> sizeof_b) > 0):
        sizeof_b += 1

    # align answer to nearest 4 bits (hex digit)
    sizeof_b += sizeof_b % 4

    return (a << sizeof_b) | b

print(hex(append_hex(a, b)))

Basically you have to find the highest set bit that b has.
Align that number to the highest multiple of 4 since that's what hex chars are.
Append the a to the front of the highest multiple of 4 that was found before.

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

I don't think you want to "append" them. Doing integer arithmetic by using strings is a bad idea. I think you want to bit-shift a into the right place and OR them together:

>>> a = 0x7B
>>> b = 0x80000
>>>
>>> hex( (a<<20) | b )
'0x7b80000'

Perhaps if you were more specific about what these numbers are and what exactly you're trying to accomplish I could provide a more general answer.

Upvotes: 5

Related Questions