Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions hex_to_dec.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
import sublime
import sublime_plugin


class HexToDecCommand(sublime_plugin.TextCommand):
MAX_STR_LEN = 20

def run(self, edit):
v = self.view
reglist = list(v.sel())
for j in range(0, len(reglist)):
hx = v.substr(v.sel()[j])
hx = hx.strip()
hexdig = '0123456789abcdefABCDEF'
l = True
if hx == '':
l = False
for i in hx:
if not(i in hexdig):
l = False

# Process selections in reverse order to prevent offset shifting
for region in reversed(list(v.sel())):
hx = v.substr(region).strip()

# Skip completely empty selections
if not hx:
continue

# Strip the 'h' or 'H' suffix if it exists
clean_hx = hx
if clean_hx.lower().endswith('h'):
clean_hx = clean_hx[:-1]

if l:
v.replace(edit, v.sel()[j], str(int(hx, 16)))
else:
try:
# Python's int() with base 16 inherently handles '0x' prefixes
dec_val = str(int(clean_hx, 16))
v.replace(edit, region, dec_val)

except ValueError:
# If int() fails, it's not a valid hex number
if len(hx) > self.MAX_STR_LEN:
logMsg = hx[0:self.MAX_STR_LEN] + "..."
else:
logMsg = hx

sublime.status_message("\"%s\" isn't a hexadecimal number!" % logMsg)
sublime.error_message("\"%s\" isn't a hexadecimal number!" % logMsg)