68 lines
2.1 KiB
Plaintext
68 lines
2.1 KiB
Plaintext
Class Utils.Number [ Abstract ]
|
|
{
|
|
|
|
ClassMethod ConvertBase10ToN(pNum As %Integer = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %String
|
|
{
|
|
If pNum=0 Quit ""
|
|
Set str=..ConvertBase10ToN(pNum\pBase, pBase, pBaseStr, pPos+1)
|
|
Quit str_$Extract(pBaseStr, pNum#pBase+1)
|
|
}
|
|
|
|
ClassMethod ConvertBaseNTo10(pStr As %String = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %Integer
|
|
{
|
|
If pStr="" Quit 0
|
|
Set num=..ConvertBaseNTo10($Extract(pStr, 1, *-1), pBase, pBaseStr, pPos+1)
|
|
Set dec=$Find(pBaseStr, $Extract(pStr, *))-2
|
|
Quit num+(dec*(pBase**pPos))
|
|
}
|
|
|
|
ClassMethod ConvertBase(pStr As %String = "", pFrom As %Integer = 10, pTo As %Integer = 10, pBaseStr As %String = "", pLen As %Integer = 0) As %String
|
|
{
|
|
// some initialisation
|
|
If pBaseStr="" Set pBaseStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
|
|
// check input values
|
|
If pFrom=10 Set pStr=$Number(pStr, "i", 0) If pStr="" Quit ""
|
|
Set pFrom=$Number(pFrom, "i", 2, 94) If pFrom="" Quit ""
|
|
Set pTo=$Number(pTo, "i", 2, 94) If pTo="" Quit ""
|
|
Set pLen=$Number(pLen, "i", 0, 32) If pLen="" Quit ""
|
|
|
|
// does base number exceed base string?
|
|
If pFrom>$Length(pBaseStr) Quit ""
|
|
If pTo>$Length(pBaseStr) Quit ""
|
|
|
|
// allow for upper/lowercase values
|
|
If pTo=10 {
|
|
If $Match(pStr, "^[0-9a-z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9A-Z]+$") {
|
|
Set pStr=$ZConvert(pStr, "U")
|
|
}
|
|
If $Match(pStr, "^[0-9A-Z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9a-z]+$") {
|
|
Set pStr=$ZConvert(pStr, "L")
|
|
}
|
|
}
|
|
|
|
// do the conversion
|
|
If pFrom=pTo {
|
|
Set pStr=pStr
|
|
} ElseIf pFrom=10 {
|
|
Set pStr=..ConvertBase10ToN($Select(pStr=0: "", 1: pStr), pTo, pBaseStr)
|
|
} ElseIf pTo=10 {
|
|
Set pStr=..ConvertBaseNTo10(pStr, pFrom, pBaseStr)
|
|
} Else {
|
|
Set pStr=..ConvertBase10ToN(..ConvertBaseNTo10(pStr, pFrom, pBaseStr), pTo, pBaseStr)
|
|
}
|
|
|
|
// return value
|
|
If pLen=0 Quit pStr
|
|
If pTo'=10 Quit ..PadStr(pStr, pLen, $Extract(pBaseStr))
|
|
Quit ..PadStr(pStr, pLen)
|
|
}
|
|
|
|
ClassMethod PadStr(pStr As %String, pLen As %Integer, pZero As %String = 0) As %String [ Private ]
|
|
{
|
|
If $Length(pStr)>pLen Quit pStr
|
|
Quit $Translate($Justify(pStr, pLen), " ", pZero)
|
|
}
|
|
|
|
}
|