From 77595ece681ddc912189516a3e85330b57e418f6 Mon Sep 17 00:00:00 2001 From: Muhammad Usman Ali <10604116+musman2015@users.noreply.github.com> Date: Fri, 3 Apr 2026 01:33:14 +0500 Subject: [PATCH] Enhance hex to decimal conversion in HexToDecCommand Refactor hex to decimal conversion logic to handle suffixes and improve error handling. --- hex_to_dec.py | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/hex_to_dec.py b/hex_to_dec.py index 8af671e..c0a94ea 100644 --- a/hex_to_dec.py +++ b/hex_to_dec.py @@ -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)