PDA

Ver la Versión Completa : ¿Cómo convertir un integer a hexadecimal?


elmago00
18-11-2014, 20:28:07
Hola que tal,
e estado intentado convertir un integer a un hexadecimal, que de como resultado:


[size - 16]

08 2A 65 13 42 65 98 22 45 00 00 00 00 00 00 00 // por que no corresponde el valor integer al este hexa


El valor integer que utilizo es 256312456892254

por ejemplo si yo convierto string a HEX:

function StringToHex(S: String): string;
var I: Integer;
begin
Result:= '';
for I := 1 to length (S) do
Result:= Result+IntToHex(ord(S[i]),2);
end;

function HexToString(H: String): String;
var I: Integer;
begin
Result:= '';
for I := 1 to length (H) div 2 do
Result:= Result+Char(StrToInt('$'+Copy(H,(I-1)*2+1,2)));
end;

y luego trato de pasar hex a string me genera un un hexa diferente.
utilizo el siguiente archivo.
3058

function StrHexaToUInt64Str(const stringHexadecimal: String): string;
var
unBigInteger:TInteger;
begin
unBigInteger:=TInteger.Create;
try
// stringHexadecimal parameter is passed without the '$' symbol
// ex: stringHexadecimal:='FFAA0256' and not '$FFAA0256'
unBigInteger.AssignHex(stringHexadecimal);
//the boolean value determine if we want to add the thousand separator or not.
Result:=unBigInteger.converttoDecimalString(false);
finally
unBigInteger.free;
end;
end;

Como hago para generar el mismo hexadecimal. lo que trato de hacer encontrar una función que genere lo mismo.
yo desconozco que función utilicen para generar ese raro valor hexadecimal con integer de 15

gracias por su respuesta

nlsgarcia
19-11-2014, 03:20:08
elmago00,


...¿Cómo convertir un Integer a Hexadecimal?...El valor Integer que utilizo es 256312456892254...Como hago para generar el mismo hexadecimal 082A6513426598224500000000000000...

:rolleyes:

Revisa este código:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, StrUtils;

type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

// Convertir Decimal a Hexadecimal
function DecToHex(Dec : UInt64): String;
var
Hex : String;
Rst : UInt64;

begin

repeat

Rst := Dec Mod 16;

if Rst = 10 Then Hex := 'A';
if Rst = 11 Then Hex := 'B';
if Rst = 12 Then Hex := 'C';
if Rst = 13 Then Hex := 'D';
if Rst = 14 Then Hex := 'E';
if Rst = 15 Then Hex := 'F';
if Rst in [0..9] then Hex := IntToStr(Rst);

Result := Result + Hex;

Dec := Dec shr 4;

until (Dec = 0);

Result := ReverseString(Result);

end;

// Convertir Hexadecimal a Decimal
function HexToDec(Hex : String): UInt64;
var
i : Integer;
M : UInt64;

begin

Result:=0;

M := 1;

Hex := AnsiUpperCase(Hex);

for i := Length(Hex) downto 1 do
begin

case Hex of
'1'..'9' : Result := Result + (Ord(Hex) - Ord('0')) * M;
'A'..'F' : Result := Result + (Ord(Hex[i]) - Ord('A') + 10) * M;
end;

M := M shl 4;

end;

end;

// Convertir Decimal a Hexadecimal
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit2.Text := DecToHex(StrToInt64(Edit1.Text));
end;

// Convertir Hexadecimal a Decimal
procedure TForm1.Button2Click(Sender: TObject);
begin
Edit2.Text := IntToStr(HexToDec(Edit1.Text));
end;

end.

El código anterior en Delphi 2010 bajo Windows 7 Professional x32, [I]convierte números de Decimal a Hexadecimal y viceversa, como se puede ver en la siguiente imagen:

http://i42.photobucket.com/albums/e305/nlsgarcia/Dec-Hex_zpsa8b0000c.jpg

Notas:

1- El rango de números enteros que puede manejar el código propuesto es de 0 a 2^64 - 1 (Tipo UInt64).

2- El número hexadecimal 082A6513426598224500000000000000 no es el equivalente del número decimal 256312456892254, como se puede ver en la siguiente imagen :

http://i42.photobucket.com/albums/e305/nlsgarcia/Convert-1_zps21ff2bfb.jpg

Tomado de : Conversor binario/decimal/hexadecimal (http://www.disfrutalasmatematicas.com/numeros/binario-decimal-hexadecimal-conversor.html)

3- Para números tan grandes (Como el hexadecimal 082A6513426598224500000000000000), [I]se requiere de una librería aritmética de precisión arbitraria, te sugiero consultar:

1-DFF Library (http://delphiforfun.org/Programs/Library/Default.htm)

2-Big Integers (http://delphiforfun.org/Programs/Library/big_integers.htm)

Espero sea útil :)

Nelson.

nlsgarcia
19-11-2014, 04:45:42
elmago00,


...¿Cómo convertir un Integer a Hexadecimal?...El valor Integer que utilizo es 256312456892254...Como hago para generar el mismo hexadecimal 082A6513426598224500000000000000...

:rolleyes:

Revisa este código:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, StrUtils, UBigIntsV4;

type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

// Convertir Decimal a Hexadecimal
procedure TForm1.Button1Click(Sender: TObject);
var
Hex : TInteger;
begin
Hex := TInteger.Create(0);
Hex.Assign(Edit1.Text);
Edit2.Text := Hex.ConvertToHexString;
Hex.Free;
end;

// Convertir Hexadecimal a Decimal
procedure TForm1.Button2Click(Sender: TObject);
var
Dec : TInteger;
begin
Dec := TInteger.Create(0);
Dec.AssignHex(Edit1.Text);
Edit2.Text := Dec.ConvertToDecimalString(False);
Dec.Free;
end;

end.

El código anterior en Delphi 2010 bajo Windows 7 Professional x32, convierte números de Decimal a Hexadecimal y viceversa por medio de DFF Library (http://delphiforfun.org/Programs/Library/Default.htm), como se puede ver en la siguiente imagen:

http://i42.photobucket.com/albums/e305/nlsgarcia/Dec-Hex-2_zps2c26a48f.jpg

Espero sea útil :)

Nelson.

ecfisa
19-11-2014, 08:31:57
Hola elmago00

...
El valor integer que utilizo es 256312456892254
...

Otra opción para la librería estándar Delphi:

...

function IntToHex64(Num: Int64): string;
var
Resto: Int64;
begin
Result:= '';
while (Num > 0) do
begin
Resto := Num mod 16;
Num := Num div 16;
Result:= IntToHex(Resto, 1) + Result
end
end;

// Decimal a hexadecimal
procedure TForm1.btnToHexClick(Sender: TObject);
begin
EditHex.Text:= IntToHex64(StrToInt64(EditDec.Text));
end;

// Hexadecimal a decimal
procedure TForm1.btnToDecClick(Sender: TObject);
begin
EditDec.Text:= IntToStr(StrToInt64('$' + EditHex.Text));
end;


http://sia1.subirimagenes.net/img/2014/11/19/141119081722294182.jpg

Saludos :)

elmago00
20-11-2014, 19:23:03
Gracias Nelson y ecfisa resolvieron gran parte de mi problema, ahora solo me queda una pregunta,

como puedo separar la cadena del Tedit en gruppo de 2.

por ejemplo :256312456892254 quisiera que quedara en string.

var1: 25
var2: 63

etc

e intentado pero solo puedo separarlo en array de char, pero los necesito en string, y debido que el TEdit no puedo usar identificador o separador, parar separar el string, se me dificulta y tampoco puedo especificar un valor, por que el usuario debe insertarlo.

si tienen tiempo para ayudarme con esto ultimo, se los agradecería mucho.

mil gracias por ayudarme siempre.

nlsgarcia
20-11-2014, 20:54:18
elmago00,


...como puedo separar la cadena del TEdit en grupos de 2...

:rolleyes:

Revisa este código:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
i : Integer;
SL : TStringList;

begin

SL := TStringList.Create;

for i := 1 to Length(Edit1.Text) do
begin
if (i mod 2) = 0 then
SL.Add(Copy(Edit1.Text,i-1,2));
end;

if (Length(Edit1.Text) mod 2) <> 0 then
SL.Add(Copy(Edit1.Text,Length(Edit1.Text),1));

ListBox1.Clear;

for i := 0 to SL.Count - 1 do
ListBox1.Items.Add(SL.Strings);

SL.Free;

end;

end.

El código anterior en Delphi 7 sobre Windows 7 Professional x32, [I]permite dividir un número en grupos de 2, como se puede ver en la siguiente imagen:

http://i42.photobucket.com/albums/e305/nlsgarcia/SplitNumber_zpscd11e522.jpg

Espero sea útil :)

Nelson.

ecfisa
20-11-2014, 20:55:29
como puedo separar la cadena del Tedit en gruppo de 2.

por ejemplo :256312456892254 quisiera que quedara en string.

var1: 25
var2: 63

etc

En ese caso creo que te conviene hacerlo a mano...

...
var
s1,s2,s3,s4,s5,s6,s7,s8: string;


procedure TForm1.btnSepararClick(Sender: TObject);
begin
with Edit1 do
begin
s1:= Copy(Text,1,2);
s2:= Copy(Text,3,2);
s3:= Copy(Text,5,2);
s4:= Copy(Text,7,2);
s5:= Copy(Text,9,2);
s6:= Copy(Text,11,2);
s7:= Copy(Text,13,2);
s8:= Copy(Text,15,2);
end;
Edit2.Text:= Format('%s %s %s %s %s %s %s %s',[s1,s2,s3,s4,s5,s6,s7,s8]);
end;


http://sia1.subirimagenes.net/img/2014/11/20/141120084855327605.jpg

Aunque logicamente, al ser un total de 15 caracteres, no es posible almacenar dos caracteres por variable ...

Saludos :)

ecfisa
21-11-2014, 06:05:17
Hola el mago00.

Para ampliar opciones, otro modo de asignar las duplas a las variables:

...
procedure HexToVars(HexStr: string; v: array of Pointer);
var
c,i: Integer;
begin
i:= Low(v);
c:= 1;
while i <= High(v) do
begin
string(v[i]^):= Copy(HexStr, c, 2);
Inc(c, 2);
Inc(i);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
v1,v2,v3,v4,v5,v6,v7,v8: string;
begin
HexToVars('256312456892254', [@v1,@v2,@v3,@v4,@v5,@v6,@v7,@v8]);
ShowMessage(Format('%s %s %s %s %s %s %s %s',[v1,v2,v3,v4,v5,v6,v7,v8]));
end;


Saludos :)

Casimiro Notevi
21-11-2014, 09:52:43
Muy ingenioso.

elmago00
22-11-2014, 21:57:17
muchas gracias el problema esta resuelto.