I'm writing a base converter because I have a test soon and I need to convert a binary number in 3 different bases: octal, decimal and hexadecimal. I've already written the code that convert a binary string into decimal and hexadecimal.
function bintodec(Value:string;dec:TEdit;hexadec:TEdit): Integer;
var //dec and hexadec are the TEdits where I will put the result
i, iValueSize: Integer;
Edit2,f:TEdit;
begin
Result := 0;
iValueSize := Length(Value);
for i := iValueSize downto 1 do
begin
if Value[i] = '1' then Result := Result + (1 shl (iValueSize - i));
end;
dec.Text:=(IntToStr(Result)); //dec. number
hexadec.Text:=(IntToHex(Result,8)); //hexadec. number
end;
As you can see here, the function takes a string (for example 10101001) and puts into 2 different edit the result.
I've made a function that convert a decimal number into an octal number but when I press the SpeedButton Calc.
I have an error. It says that project1 raised a class exception 'External: SIGSEGV' and then near to Unit1 I see the page control.inc. I've searched on google a solution but I didn't find useful answers.
function dec2oct(mystring:Integer): String;
var
a: String;
getal_met_rest : Double;
Edit2:TEdit;
begin
while mystring> 0 do
begin
getal_met_rest := getal / 8;
a:= a + IntToStr(mystring - (trunc(getal_met_rest)*8));
getal := trunc(getal_met_rest);
end;
dec2oct:=ReverseString(a);
Edit2.text:=dec2oct
end;
I didn't find a way for binary-octal conversion, so once I've converted from binary to decimal, I call the function dec2oct
. I call the functions in this way:
var a:smallint;
begin
bintodec(Edit1.Text,Edit3,Edit4);
dec2oct(Edit3.Text); //Edit3 contains the number on base 10
end;
Could you help me?
I would usually use string or character arrays and bit arithmetic for such conversions. For instance:
function Int2Oct(invalue: integer): ShortString;
const
tt: array[0..7] of char = ('0', '1', '2', '3', '4', '5', '6', '7');
var
tempval: integer;
begin
Result := '';
tempval := invalue;
if tempval = 0 then
Result := '0'
else
while (tempval <> 0) do
begin
Result := tt[(tempval and $7)] + Result;
tempval := (tempval shr 3);
end;
end;
Seems to work in the short little bit of time that I tested it as long as you don't expect it to handle negative numbers. Edit: It handles zero now.