Convert Value to 32-bit values - python

I have a table Widget and user give a number in table, so when I get this value I want to convert 32 bit hex value.
For example user enter number 10, I need to convert this number
Firstly 0x000A (it need to be hex)
And split like this myList = [0x0,0x0,0x0,0xA]
I tried with below command
myNum = 10
value = '0x{0:04X}'.format(myNum)
print(value)
print(list(struct.pack('<H',value)))
I get struct.error: required argument is not an integer
'0x{0:04X}'.format(myNum) value return string so I couldnt split this value correctly.
I expect this value [0x0,0x0,0x0,0xA]
How can I do that ?

You cannot do a strut.pack on a string. It takes integers (as the error describes) and returns a byte string, which you can turn into a list.
import struct
myNum = 10
myHex = '0x{0:04X}'.format(myNum)
print(myHex)
mylist = list(struct.pack('>I',myNum))
print(mylist)
print(list(map(hex, mylist)))
The last line prints them as hex, but they are not integers, they are strings. And you are trying to use little endian in your code, but the expected output is in Big.

Related

Convert int to hex of a given number of characters

I want to convert my int number into an hex one specifying the number of characters in my final hex representation.
This is my simple code that takes an input an converts it into hex:
my_number = int(1234)
hex_version = hex(my_number)
This code returns a string equal to 0x4d2.
However I would like my output to contain 16 characters, so basically it should be 0x00000000000004d2.
Is there a way to specify the number of output character to the hex() operator? So that it pads for the needed amount of 0.
From Python's Format Specification Mini-Language:
n = int(1234)
h = format(n, '#018x')
The above will generate the required string. The magic number 18 is obtained as follows: 16 for the width you need + 2 for '0' (zero) and 'x' (for the hex descriptor string prefix).

Convert string to hexadecimal with "0x" and leading 0s in Python

I want to change a registry key value via Python. The value type will be REG_DWORD which means hexadecimal including 0x000 in integer format. I am having trouble converting a string with a number to its hexadecimal format in integer.
Since I am looping through a number of registry keys, my code to change a certain key is as follows:
for i in range(len(checking_names)): #loop through names to check
if checking_names(i) !== should_values(i): #no match
with winreg.CreateKeyEx(key, subkey_path, 0, winreg.KEY_ALL_ACCESS) as subkey:
winreg.DeleteValue(subkey, names_data[i]) #have to delete name in order to overwrite
winreg.SetValueEx(subkey, names_data[i], 0, winreg.REG_DWORD, new_hex_value) #overwrite name value with correct value from predefined list
My values_data list is comprised of predefined variables as strings. One of the entries is a string '9600'. In my above code, values_data[i] should be 9600 in hexadecimal format: 0x00002580. For this conversion I do the following:
dec_to_hex_str = format(int(values_data[i]),'x') #string decimal to string hexadecimal conversion
zeros_pre_x = '0x' #0x for format 0xffffffff
zeros_to_add = 8 - len(dec_to_hex_str) #count number of leading 0s to add
mid_zeros_list = []
for j in range(zeros_to_add):
mid_zeros_list.append(0) #add a leading 0
mid_zeros = ''.join(mid_zeros_list) #convert list to string
new_hex_value = int(zeros_pre_hex + mid_zeros + dec_to_hex_str)
When I run this code, my Python shell is unresponsive, and there is no change in the Windows registry for the subkey value. The problem seems to be, that winreg.SetValueEx .... winreg.REG_DWORD only understands integer format but my new_hex_value is not being properly converted from string to integer.
Any help would be appreciated!
Your problem lies in the line
new_hex_value = int(zeros_pre_hex + mid_zeros + dec_to_hex_str)
You are converting the number to a hex string, then converting it into an integer. Not only is this an invalid argument to int(), but even if it were correct, you would just be converting it back to an integer (there is no such thing as a hex integer in Python). So your line should read:
new_hex_value = zeros_pre_hex + mid_zeros + dec_to_hex_str
Then simply write this as a REG_SZ because you want a hex string, not an integer. There is no "hex integer" in the registry either.

How to turn a binary string into a byte?

If I take the letter 'à' and encode it in UTF-8 I obtain the following result:
'à'.encode('utf-8')
>> b'\xc3\xa0'
Now from a bytearray I would like to convert 'à' into a binary string and turn it back into 'à'. To do so I execute the following code:
byte = bytearray('à','utf-8')
for x in byte:
print(bin(x))
I get 0b11000011and0b10100000, which is 195 and 160. Then, I fuse them together and take the 0b part out. Now I execute this code:
s = '1100001110100000'
value1 = s[0:8].encode('utf-8')
value2 = s[9:16].encode('utf-8')
value = value1 + value2
print(chr(int(value, 2)))
>> 憠
No matter how I develop the later part I get symbols and never seem to be able to get back my 'à'. I would like to know why is that? And how can I get an 'à'.
>>> bytes(int(s[i:i+8], 2) for i in range(0, len(s), 8)).decode('utf-8')
'à'
There are multiple parts to this. The bytes constructor creates a byte string from a sequence of integers. The integers are formed from strings using int with a base of 2. The range combined with the slicing peels off 8 characters at a time. Finally decode converts those bytes back into Unicode characters.
you need your second bits to be s[8:16] (or just s[8:]) otherwise you get 0100000
you also need to convert you "bit string" back to an integer before thinking of it as a byte with int("0010101",2)
s = '1100001110100000'
value1 = bytearray([int(s[:8],2), # bits 0..7 (8 total)
int(s[8:],2)] # bits 8..15 (8 total)
)
print(value1.decode("utf8"))
Convert the base-2 value back to an integer with int(s,2), convert that integer to a number of bytes (int.to_bytes) based on the original length divided by 8 and big-endian conversion to keep the bytes in the right order, then .decode() it (default in Python 3 is utf8):
>>> s = '1100001110100000'
>>> int(s,2)
50080
>>> int(s,2).to_bytes(len(s)//8,'big')
b'\xc3\xa0'
>>> int(s,2).to_bytes(len(s)//8,'big').decode()
'à'

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.
You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'
Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer
Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

Why does Python remove leading zeroes when converting from string to int?

>>> num = int('0241034812')
>>> print(num)
241034812
>>>
In the above code, I'm setting the variable num to 0241034812; however, when I print the variable it deletes the first zero.
Why is this happening?
Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.
You can use the following syntax to add leading zeros to an integer:
print "%010d" % (241034812,)
The example above will display the integer 241034812 with 10 digits as 0241034812.
I'm setting the variable 'num' to '0241034812'
No, you're setting it to 241,034,812: an integer value, about two hundred forty million. If you want to set it to '0241034812', you should use a string rather than an integer. That is, you should drop the call to int:
>>> num = '0241034812'
>>> print(num)
0241034812
>>>
If you're storing some number in a format where a leading zero would be useful/significant (maybe a barcode, ISBN, or the like), you can re-add them when converting back into a string using .format
>>> num = int('0241034812')
>>> print('{:010d}'.format(num))
0241034812
Briefly, the first 0 in the format spec means to add leading zeros if not present to fill 10 (the 10) characters.
You wanted to print your integer to a specific zero-padded width, use string formatting. The format() function, for example:
>>> num = 241034812
>>> print(format(num, '010d'))
0241034812
or print the original string from which you parsed the integer in the first place.
Integers do not store a 'print width' or any number of leading 0 digits.

Categories

Resources