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

0

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!

python
format
hex
registry
winreg
asked on Stack Overflow Feb 18, 2021 by needhelp123456 • edited Feb 18, 2021 by needhelp123456

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0