Dúvida para converter binário p/ decimal
Estou usando o seguinte exemplo:
function BinToInt(Value: string): Integer;
var
i, iValueSize: Integer;
begin
Result := 0;
iValueSize := Length(Value);
for i := iValueSize downto 1 do
if Value = ´1´ then Result := Result + (1 shl (iValueSize - i));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
label2.Caption:=´O número decimal é: ´+ IntToStr(BinToInt(Edit1.Text));
end;
[color=blue:e9d9e46746]Gostaria de adicionar o seguinte: se o usuário digitar no Edit1 um número que não é binário, apareça no label2 isto, ´Você não digitou um número binário´. Será que isto é possível com esta função? Não consegui resolver, se alguém puder me ajudar agradeço.[/color:e9d9e46746] :cry:
function BinToInt(Value: string): Integer;
var
i, iValueSize: Integer;
begin
Result := 0;
iValueSize := Length(Value);
for i := iValueSize downto 1 do
if Value = ´1´ then Result := Result + (1 shl (iValueSize - i));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
label2.Caption:=´O número decimal é: ´+ IntToStr(BinToInt(Edit1.Text));
end;
[color=blue:e9d9e46746]Gostaria de adicionar o seguinte: se o usuário digitar no Edit1 um número que não é binário, apareça no label2 isto, ´Você não digitou um número binário´. Será que isto é possível com esta função? Não consegui resolver, se alguém puder me ajudar agradeço.[/color:e9d9e46746] :cry:
Ginosam
Curtidas 0
Respostas
Cassio Marques
20/06/2003
O código do botão poderia ficar assim:
procedure TForm1.Button1Click(Sender: TObject);
Var i : Integer;
begin
for i := Length(edit1.text) downto 1 do
If (Copy(edit1.text,i,1) <> ´0´) and (Copy(edit1.text,i,1) <> ´1´) then
begin
label2.Caption := ´O número não é binário´;
exit;
end
else
label2.Caption:=´O número decimal é:´+ IntToStr(BinToInt(Edit1.Text));
end;
procedure TForm1.Button1Click(Sender: TObject);
Var i : Integer;
begin
for i := Length(edit1.text) downto 1 do
If (Copy(edit1.text,i,1) <> ´0´) and (Copy(edit1.text,i,1) <> ´1´) then
begin
label2.Caption := ´O número não é binário´;
exit;
end
else
label2.Caption:=´O número decimal é:´+ IntToStr(BinToInt(Edit1.Text));
end;
GOSTEI 0
Cassio Marques
20/06/2003
Fiz um teste com a função que calcula o decimal do número binário e não funcionou... alterei a função de forma que a mesma calcule o valor corretamente....... OK?
function BinToInt(Value: string): Integer;
var
i, iValueSize, Contador: Integer;
begin
Result := 0;
iValueSize := Length(Value);
Contador := 1;
for i := iValueSize downto 1 do
Begin
if Copy(Value,i,1) = ´1´ then Result := Result + Contador;
Contador := Contador * 2;
end;
end;
function BinToInt(Value: string): Integer;
var
i, iValueSize, Contador: Integer;
begin
Result := 0;
iValueSize := Length(Value);
Contador := 1;
for i := iValueSize downto 1 do
Begin
if Copy(Value,i,1) = ´1´ then Result := Result + Contador;
Contador := Contador * 2;
end;
end;
GOSTEI 0
Ginosam
20/06/2003
Meu amigo Cassio Marques, testei o seu último exemplo e conclui que o mesmo está igual ao meu! Veja, se eu estiver errado me corrija, um número binário é formado só por ´0´ e ´1´, certo. No meu exemplo, se você colocar 101001, a resposta será o número decimal 41. No seu exemplo, também será 41! Agora se eu colocar o número 12 no meu ou no seu exemplo, a resposta deveria ser: ´este número não é binário´, concorda, e não a resposta decimal 2. Veja a calculadora do windows no modo científico, deixe-a em binário, coloque 101001 e passe para decimal. Que valor achou? 41, né? Agora, deixe-a em binário novamente e experimente colocar o número 12! Impossível não é? Sim, somente os números ´0´ e ´1´ do tecladinho estão habilitados, né? Conclusão, nem o meu e nem o seu exemplo ainda está perfeito! Agradeço, e se você ou outra pessoa puder nos ajudar, beleza! T+
GOSTEI 0
Thaisandrade
20/06/2003
ginosan, fiz essa função mas não a uso a algum tempo. Dê uma olha e veja se ela te ajuda. Me informa por favor. Mais a baixo está a função auxiliar ´potencia´
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
GOSTEI 0
Thaisandrade
20/06/2003
ginosan, fiz essa função mas não a uso a algum tempo. Dê uma olha e veja se ela te ajuda. Me informa por favor. Mais a baixo está a função auxiliar ´potencia´
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
GOSTEI 0
Renaldo
20/06/2003
www.clubedelphi.com.br
dicas e macetes
controlando digitação no edit
Isto é a resposta a suas dúvidas.
dicas e macetes
controlando digitação no edit
Isto é a resposta a suas dúvidas.
GOSTEI 0
Ginosam
20/06/2003
thaisandrade, valeu, testei o seu exemplo, ele funciona sim. Mas a função Potencia deve ser declarada primeiro, senão aparece undeclared Potencia... Veja como ficou:
implementation
{$R *.dfm}
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
label1.Caption:=´O número decimal é: ´+ IntToStr(BinToInt(Edit1.Text));
end;
Obrigado, Mano. Ah... só para mostrar o que eu tinha adicionado no meu outro exemplo:
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key= VK_NumPad2) or (key= VK_NumPad3) or (key= VK_NumPad4) or
(key= VK_NumPad5) or (key= VK_NumPad6) or (key= VK_NumPad7) or
(key= VK_NumPad8) or (key= VK_NumPad9) then
begin
label2.Caption:=´Digite somente ´0´ e ´1´ ´;
button1.Enabled:=false;
edit1.Text:=´´;
end;
end;
implementation
{$R *.dfm}
function Potencia(Base, Expoente: Double): Double;
begin
if Base = 0 then
Result:=0
else
if Base < 0 then
Result:= Exp(Ln(-Base)*Expoente)
else
Result:= Exp(Ln(Base)*Expoente);
end;
function BinToInt(Texto: string): Int64;
var
X,Val: integer;
Aux: Double;
begin
Aux:=0;
for X:= Length(Texto) downto 1 do
begin
if (Texto[X] <> ´0´) and (Texto[X] <> ´1´) then
begin
raise Exception.Create(´Número binário inválido!´);
end;
if Texto[X] = ´1´ then
begin
Aux:= Aux+Potencia(2,Length(Texto)-X);
end;
end;
Val:= StrToInt(FloatToStr(Aux));
Result:= Val;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
label1.Caption:=´O número decimal é: ´+ IntToStr(BinToInt(Edit1.Text));
end;
Obrigado, Mano. Ah... só para mostrar o que eu tinha adicionado no meu outro exemplo:
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key= VK_NumPad2) or (key= VK_NumPad3) or (key= VK_NumPad4) or
(key= VK_NumPad5) or (key= VK_NumPad6) or (key= VK_NumPad7) or
(key= VK_NumPad8) or (key= VK_NumPad9) then
begin
label2.Caption:=´Digite somente ´0´ e ´1´ ´;
button1.Enabled:=false;
edit1.Text:=´´;
end;
end;
GOSTEI 0
Thaisandrade
20/06/2003
ginosam, toda funcão deve ser declarada primeiro. Apenas o que eu havia colocado, não era o código completo, somente as duas funções.Mas legal que tenha funcionado. Se eu puder ajudar em mais alguma coisa.
GOSTEI 0