Python hex with leading zeros

Padding a hexadecimal string with zeros

I am guaranteed to never see more than 8 digits, so this case does not need to be handled.

Right now, I have this coded as:

padded = '0x' + '0' * (10 - len(mystring)) + mystring[2:] 

It works, but feels ugly and unpythonic. Any suggestions for a cleaner method?

3 Answers 3

Perhaps you’re looking for the .zfill method on strings. From the docs:

Help on built-in function zfill: zfill(. ) S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. 

Your code can be written as:

def padhexa(s): return '0x' + s[2:].zfill(8) assert '0x00000123' == padhexa('0x123') assert '0x00ABCD12' == padhexa('0xABCD12') assert '0x12345678' == padhexa('0x12345678') 

I would suggest interpreting the input as a number, then using standard number-formatting routines.

padded = str.format('0x', int(mystring, 16)) 

The string → int → string round trip may seem silly, but it is also beneficial in that it provides validation of the input string.

I’d use something like this:

def format_word(word, prefix=None, size=None): if prefix is None: prefix = '0x' if size is None: size = 2 if not isinstance(word, int): word = int(word, 16) if word > 2**(8 * size) - 1: raise ValueError('word too great') return 'X>'.format( prefix=prefix, word=word, padding=2 * size) 

Using None as defaults and assigning true defaults later makes it easier to wrap the function.

def format_word(word, prefix=None, size=None): if prefix is None: prefix = '0x' if size is None: size = 2 

If word isn’t already a int try to convert it. It’ll choke if it’s not a str , bytes , or bytearray . We need the type check because int(word, 16) would choke if word was already an `int.

if not isinstance(word, int): word = int(word, 16) 

Check that the word isn’t going break the formatting.

if word > 2**(8 * size) - 1: raise ValueError('word too great') 

Finally, format the word, using keywords to decouple the string to the argument order.

return 'X>'.format( prefix=prefix, word=word, padding=2 * size) 

Источник

Add leading zero to hex values in python

Question: I have a list of hex bytes strings like this (as read from a binary file) I want to flip the list and append the list together to create one hex number, How do I format the list to this format? You want to use a argument to make sure the range is distinct pairs, rather than overlapping pairs.

Add leading zero to hex values in python

I have the following hex values, which i have in a file.

ff00 928a 6275 7474 6f6e 4c69 7374 df00 84ff 002a 8869 6e70 7574 5069 6e41 0185 426e 616d 6588 4a41 4a41 4a41 4441 8672 656c 6179 73c8 4103 4103 4103 4103 ff00 2a88 696e 7075 7450 696e 4102 8542 6e61 6d65 884e 454a 4e45 4a44 4186 7265 6c61 7973 c841 0441 0441 0441 04ff 0027 8869 6e70 7574 5069 6e41 0385 426e 616d 6585 4d41 4144 4186 7265 6c61 7973 c841 0141 0141 0141 01 

I want to split these hex values up in single bytes like ff and add the leading zero 0x, so i can put it directly into a unsigned char array in C.

I’ve tried by loading the hex values into python and removed all whitespaces and afterwards setting a whitespace by every other char so they’re represented as single bytes. But no matter what i can’t seem to change the layout of the hex values.

 with open ("yes.txt", "r") as myfile: byte=myfile.read().replace('\n', '').replace(' ','') [byte[i:i+2] for i in xrange(1,len(byte))] print byte 

Can someone please help me.

Assuming you want to read the values from a file and write them back in the new format that is, from a file of content «ff00 928a» get a new file with the content «0xff 0x00 0x92 0x8a» this code should do the trick:

with open("vals.txt") as f: hexVals = f.read() with open("out.txt", "w") as g: for val in hexVals.split(): g.write('0x' + val[:2] + " ") if(len(val) > 2): g.write('0x' + val[2:] + " ") 

EDIT
If the file is binary (when you print f.read() you don’t see the values you give but what they represent in ascii, you can do

from binascii import hexlify hexVals = hexlify(f.read()) 

see if printing this gives you a string with the hex representation of the data. And of course, you can convert it back with unhexlify from the same module, if needed.

Your list comprehension does return something useful—a list of every pair of characters.

It does have a couple problems, though: You’re returning every pair of characters, 1-2, then 2-3, then 3-4. You want to use a step argument to make sure the range is distinct pairs, rather than overlapping pairs. And you want to start from 0, not 1, so you don’t skip the first character.

More importantly, you don’t do anything with that list, so that isn’t very helpful.

The first thing to do is assign it to a variable:

pairs = [byte[i:i+2] for i in xrange(0, len(byte), 2)] 

Now, you can use another comprehension (or an explicit for statement) to add the 0x to each one:

c_pairs = ['0x' + pair for pair in pairs] 

And then you can join them all up with commas:

c_initializer = ', '.join(c_pairs) 

It’s worth noting that you could just as easily use generator expressions instead of list comprehensions here, saving a bit of memory. And you can merge the separate steps together, too.* For example:

c_initializer = ', '.join('0x' + byte[i:i+2] for i in xrange(0, len(byte), 2)) 

You probably also want to stick some braces around the string, and write it out somewhere, but I’ll leave that part as an exercise for the reader; the fact that you know how to use file.read and str.replace means you can probably handle these similar tasks pretty easily.

* Although if you merge all the steps together, as I did, replacing the single list comprehension with a generator expression doesn’t actually add any benefit anymore, because if you give str.join an iterator it just makes a list out of it anyway.

Add zeros to a float after the decimal point in Python, Correct me if I am wrong, but this also has the implicit instruction of «round to 6 decimal places» not just «keep 6 decimal places». So while it makes sense in the context of all zeros, the reason one might go to the precision is implied that you may actually USE that precision, as such you may need to go out further (and …

Padding a hexadecimal string with zeros

I’m given a hexadecimal number in string form with a leading «0x» that may contain 1-8 digits, but I need to pad the number with zeros so that it always has 8 digits (10 characters including the «0x» ).

  • «0x123» should become «0x00000123» .
  • «0xABCD12» should become «0x00ABCD12» .
  • «0x12345678» should be unchanged.

I am guaranteed to never see more than 8 digits, so this case does not need to be handled.

Right now, I have this coded as:

padded = '0x' + '0' * (10 - len(mystring)) + mystring[2:] 

It works, but feels ugly and unpythonic. Any suggestions for a cleaner method?

Perhaps you’re looking for the .zfill method on strings. From the docs:

Help on built-in function zfill: zfill(. ) S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. 

Your code can be written as:

def padhexa(s): return '0x' + s[2:].zfill(8) assert '0x00000123' == padhexa('0x123') assert '0x00ABCD12' == padhexa('0xABCD12') assert '0x12345678' == padhexa('0x12345678') 

I would suggest interpreting the input as a number, then using standard number-formatting routines.

padded = str.format('0x', int(mystring, 16)) 

The string → int → string round trip may seem silly, but it is also beneficial in that it provides validation of the input string.

I’d use something like this:

def format_word(word, prefix=None, size=None): if prefix is None: prefix = '0x' if size is None: size = 2 if not isinstance(word, int): word = int(word, 16) if word > 2**(8 * size) - 1: raise ValueError('word too great') return 'X>'.format( prefix=prefix, word=word, padding=2 * size) 

Using None as defaults and assigning true defaults later makes it easier to wrap the function.

def format_word(word, prefix=None, size=None): if prefix is None: prefix = '0x' if size is None: size = 2 

If word isn’t already a int try to convert it. It’ll choke if it’s not a str , bytes , or bytearray . We need the type check because int(word, 16) would choke if word was already an `int.

if not isinstance(word, int): word = int(word, 16) 

Check that the word isn’t going break the formatting.

if word > 2**(8 * size) - 1: raise ValueError('word too great') 

Finally, format the word, using keywords to decouple the string to the argument order.

return 'X>'.format( prefix=prefix, word=word, padding=2 * size) 

Python — Conversion a hex string adding 0x30 to each, Add 0x30 to ‘0’ and get 0x30. Add 0x30 to ‘3’ and get 0x33. Add 0x30 to ‘F’ and get 0x3F. Add 0x30 to ‘E’ and get 0x3E. Add 0x30 to ‘5’ and get 0x35. Finally get them to a string obtaining ’03?>5′ which are the ascii results. I’ve tried several things but maybe this are the closest to the right one:

How to append a list of Hex to one Hex number

I have a list of hex bytes strings like this

I want to flip the list and append the list together to create one hex number,

How do I format the list to this format?

Concatenate your hex numbers into one string:

'0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)]) 

This does include the 00 byte explicitly in the output:

>>> inputlist = ['0xe1', '0xd7', '0x7', '0x0'] >>> '0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)]) '0x0007D7E1' 

However, I’d look into reading your binary file format better; using struct for example to unpack bytes directly from the file into proper integers in the right byte order:

>>> import struct >>> bytes = ''.join([chr(int(c, 16)) for c in inputlist]) >>> value = struct.unpack('>> print hex(value) 0x7d7e1 

Python 3.7 — How to remove ‘0x’ in hex and get 2 digits, Res = 0x0 0x1a 0x9 0x14 0x13 0x0. I want to — remove the ‘0x’ from the beginning of each -have 2 digits — and to remove the spaces in between. i.e I want to have the Res like this: 001a09141300. I tried .join but then I …

Python regex \number adding \0x

I am tring to go a simple regex replace on a string in python. This is my code:

>>> s = "num1 1 num2 5" >>> re.sub("num1 (.*?) num2 (.*?)","1 \1 2 \2",s) 

I would expect an output like this, with the \number s being replaced with their corresponding groups.

However, this is the output I am getting:

And I’m kinda stumped as to why the \x0 s are their, and not what I would like to be there. Many thanks for any help

You need to start using raw strings (prefix the string with r):

>>> import re >>> s = "num1 1 num2 5" >>> re.sub(r"num1 (.*?) num2 (.*?)", r"1 \1 2 \2", s) '1 1 2 5' 

Otherwise you would need to escape your backslashes both for python and for the regex, like this:

>>> re.sub("num1 (.*?) num2 (.*?)", "1 \\1 2 \\2", s) '1 1 2 5' 

(this gets really old really fast, check out the opening paragraphs of the python regex docs

\1 and \2 are getting interpreted as octal character code escapes, rather than just getting passed to the regex engine. Using raw strings r»\1″ instead of «\1» prevents this interpretation.

The \1 is being interpreted in the string. So you must escape the \ with its own backslash:

>>> re.sub("num1 (.*?) num2 (.*?)", "1 \\1 2 \\2",s) '1 1 2 5' 

You can also use a raw string:

>>> re.sub("num1 (.*?) num2 (.*?)", r"1 \1 2 \2",s) '1 1 2 5' 

Python — Adding/Subtracting Hexadecimals, 1 Answer. basehex = input () sechex = input () basehexin = int (basehex, 16) sechexin = int (sechex, 16) sum = basehexin — sechexin print (hex (sum)) This code will do it, by converting the hexadecimals to decimals, subtracting them, then converting (representing) them to hexadecimals again. Note that int …

Источник

Читайте также:  Instance function in java
Оцените статью