Something to get the creative juices flowing in the new year - A simple and cross-platform class to convert a value from one base to another.
/* dotr.math.BaseConversion.cls
Licenced under The MIT License
Copyright (c) 2012 Julian Lyndon-Smith
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using Progress.Lang.*.
class dotr.math.BaseConversion:
/** converts 0 .. 9 into hex value
* @param value to convert
* @return hex char of value
*/
method private char toChar(p_value as int):
return substr("0123456789ABCDEF",p_Value + 1,1).
end method.
/** returns hex value of integer passed in
* @param value to convert
* @param base to use
* @return hex value of value
*/
method public char toHex (p_value as int,p_base as int):
def var remainder as int no-undo.
assign remainder = p_value mod p_Base.
if remainder eq p_value then return toChar(p_value).
return toHex( int((p_value - remainder) / p_base ),p_base) + toChar(remainder).
end method.
/** returns integer value of base value passed in
* @param value to convert
* @param base to use
* @return int value of base value
*/
method public int toInt (p_value as char,p_base as int):
def var i as int no-undo.
def var power as int no-undo.
def var result as int no-undo.
do i = length(p_value) to 1 by -1:
assign result = result + exp(p_base,power) * (index("0123456789ABCDEF",substr(p_value,i,1)) - 1).
power = power + 1.
end.
return result.
end method.
end class.
both these methods seem very fast, so here's the challenge - what further optimizations can be made ?
Oh, and can we claim the first ABL open source contribution of the year ?