Ir al contenido


Foto

Convertir un numero entero MUY largo a hexadecimal o binario


  • Por favor identifícate para responder
1 respuesta en este tema

#1 seoane

seoane

    Advanced Member

  • Administrador
  • 1.259 mensajes
  • LocationEspaña

Escrito 12 febrero 2022 - 12:09

El siguiente código muestra como convertir un numero entero muy largo, por ejemplo de 100 cifras, a hexadecimal o binario


php
  1. type
  2. TBigInt = Array of Byte;
  3.  
  4. function parseBigInt(str: String): TBigInt;
  5. var
  6. i, l: Integer;
  7. begin
  8. if Length(str) = 0 then
  9. raise Exception.Create('Invalid integer value');
  10. while (Length(str) > 1) and (str[1] = '0') do
  11. delete(str, 1, 1);
  12. l:= Length(str);
  13. SetLength(Result, l);
  14. for i:= 1 to l do
  15. Result[l - i]:= StrToInt(str[i]);
  16.  
  17. function div2(bigInt: TBigInt): TBigInt;
  18. var
  19. i, j, rem: Integer;
  20. begin
  21. rem:= 0;
  22. for i:= High(bigInt) downto Low(bigInt) do
  23. begin
  24. j:= rem + bigInt[i];
  25. bigInt[i]:= j div 2;
  26. rem:= (j mod 2) * 10;
  27. end;
  28. Result:= bigInt;
  29.  
  30. function bigIntOdd(bigInt: TBigInt): Boolean;
  31. begin
  32. if Length(bigInt) < 1 then
  33. Result:= True
  34. else
  35. Result:= Odd(bigInt[Low(bigInt)]);
  36.  
  37. function isZero(bigInt: TBigInt): Boolean;
  38. var
  39. i: Integer;
  40. begin
  41. Result:= True;
  42. for i:= Low(bigInt) to High(bigInt) do
  43. if bigInt[i] <> 0 then
  44. begin
  45. Result:= False;
  46. end;
  47.  
  48. function bigIntToBinary(bigInt: TBigInt): String;
  49. begin
  50. Result:= '';
  51. while not isZero(bigInt) do
  52. begin
  53. if bigIntOdd(bigInt) then
  54. Result:= '1' + Result
  55. else
  56. Result:= '0' + Result;
  57. bigInt:= div2(bigInt);
  58. end;
  59.  
  60. function binaryToHex(binary: String): String;
  61. var
  62. i,j,k: Integer;
  63. nibble: String;
  64. begin
  65. Result:= '';
  66. while Length(binary) mod 4 <> 0 do
  67. binary:= '0' + binary;
  68. if Length(binary) = 0 then
  69. begin
  70. Result:= '0';
  71. end;
  72. for i:= 0 to (length(binary) div 4) - 1 do
  73. begin
  74. nibble:= Copy(binary, (4*i)+1, 4);
  75. k:= 0;
  76. for j:= 1 to length(nibble) do
  77. begin
  78. k:= k * 2;
  79. if nibble[j] = '1' then k:= k + 1;
  80. end;
  81. Result:= Result + IntToHex(k, 1);
  82. end;

Por ejemplo esto


php
  1. Writeln(binaryToHex(bigIntToBinary(parseBigInt('9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210'))));

Genera esto a la salida


php
  1. 120FE0BCDADD3B9A1BD4E0782C2D3E04397663BB69D67059E9426DD4733C9B4067DED51E67D751C67EEA

Saludos


  • 0

#2 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 14 febrero 2022 - 09:50

Excelente solución amigo Seoane, un gusto verte por aquí.

Saludos


  • 0




IP.Board spam blocked by CleanTalk.