Programmer's Notepad - a Calculator?!

One of the recent feature requests for Programmer’s Notepad was to add the ability in PN to perform basic numeric conversions, e.g. decimal to hex. Also the ability to evaluate simple mathematical expressions like 2+3=.

With the PyPN extension this is very easy, and the required features can even be bound to keyboard shortcuts.

Number Conversions:

The first thing we might want to do is see hex, decimal, octal or even binary representations of a selected number. The following script plus helper functions does this for decimal or hex selections:

[sourcecode language=”python”] import pn, scintilla

def hex2dec(s): “"”return the integer value of a hexadecimal string s””” return int(s, 16)

def Denary2Binary(n): “"”convert denary integer n to binary string bStr””” bStr = ‘’ if n < 0: raise ValueError, “must be a positive integer” if n == 0: return ‘0’ while n > 0: bStr = str(n % 2) + bStr n = n » 1 return bStr

@script(“ConvertNumber”) def ConvertNumber(): s = scintilla.Scintilla(pn.CurrentDoc()) if s.SelectionEnd - s.SelectionStart < 1: return sel = s.SelText if sel.find(‘0x’) != -1: sel = sel.replace(“0x”, “”) sel = hex2dec(sel) else: sel = int(sel) pn.AddOutput(“Dec: %d\n” % sel) pn.AddOutput(“Hex: 0x%X\n” % sel) pn.AddOutput(“Oct: %o\n” % sel) pn.AddOutput(“Bin: %s” % Denary2Binary(sel)) [/sourcecode]

In the next post we’ll look at evaluating simple math expressions.