Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Display a value in a different base like hex or binary

Title: Display a value in a different base like hex or binary. Question: Sometimes, you need to change the base system of a decimal number, foer example you want to display a decimal number x to its hexadecimal equilivant, or octal, or binary! Or even switch between hexadecimal and binary! This article describes an standard way how to do this and encapsulates the whole in a component where you can change the in- and outbase from 2 to 36. Answer: In Delphi, you can only calculate in a decimal system or hexadecimal. But there is no way to change to another system. Therefore, you already need 2 functions: 1. One to transform a decimal number to another basesystem. I will name this function _10ToB 2. And one to tranform a number from any system to decimal. This will be the function _Bto10 With these 2 functions, you will be able to switch from any base system to another, by the midway of first tranforming the number in a decimal format (_Bto10), and then to the desired base system (_10toB). Here are the 2 functions in detail. An array of char (Trans) is needed to make a display possible: const Trans : array[0..35] of char = ('0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J', 'K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z') ; function _10ToB (ID : integer; b : integer) : string ; begin Result := '' ; while ID 0 do begin Result := Trans[ID mod b] + Result ; ID := ID div b ; end ; if Result = '' then Result := '0'; end; function _BTo10 (BC : string ; b : integer ) : integer ; var x : char ; i, k, L : integer ; Found : boolean ; begin Result := 0 ; Invalid := false ; L := Length(BC) ; for i := 0 to L-1 do begin x := BC[L-i] ; k := 0 ; Found := false ; repeat if x = Trans[k] then found := true else k := k + 1 ; until (k b-1) or Found ; if found then Result := Result + k*Pow(b,i) { Pow is a function that calculates b^i } else begin Invalid := true ; Result := 0 ; Exit ; end ; end ; end; I have included the whole thing in a component that you may download from http://www.rhrk.uni-kl.de/~peiffer/downloads/BaseSwitcher.zip Tom Peiffer