问题描述
我正在写一个基本转换器,因为我即将进行测试,我需要将二进制数转换为3个不同的基数:八进制,十进制和十六进制.我已经编写了将二进制字符串转换为十进制和十六进制的代码.
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;
如您在此处看到的,该函数接受一个字符串(例如10101001),并将结果放入2种不同的编辑中.
As you can see here, the function takes a string (for example 10101001) and puts into 2 different edit the result.
我已经做了一个将十进制数字转换为八进制数字的函数,但是当我按下SpeedButton Calc.
时,我遇到了一个错误.它说project1引发了一个类异常'External:SIGSEGV',然后靠近Unit1,我看到了页面control.inc.我在Google上搜索了一个解决方案,但没有找到有用的答案.
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;
我没有找到进行二进制八进制转换的方法,所以一旦我从二进制转换为十进制,就调用函数dec2oct
.我以这种方式调用函数:
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;
你能帮我吗?
推荐答案
对于这种转换,我通常会使用字符串或字符数组和位算术.例如:
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. It handles zero now.
这篇关于基本转换器二进制到八进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!