Ir al contenido


Foto

[RESUELTO] Conversiones binarias y strings


  • Por favor identifícate para responder
28 respuestas en este tema

#1 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 04 agosto 2011 - 04:01

Les comento que tengo que hacer un pequeño programa en algo llamado iRev (lenguaje dedicado que se usa para controladores industriales) el lenguaje es una mezcla de Pascal, VB, C, aunque su programacion esta fuertemente orientada a Pascal pero no cuenta con todas las bibliotecas, es bastante limitado. Mi pequeño problema en este momento es como convertir un numero o representacion binaria a un string ASCII.




delphi
  1. POSICION |  7  6  5 4 3 2 1 |
  2. VALOR    | 64 32 16 8 4 2 1 |
  3. -----------------------------
  4. SWA        0  1  0 1 0 0 1
  5. -----------------------------
  6. SWB      |  0  1  1 0 0 0 0
  7. SWB      |  0  1  1 1 0 0 0
  8. SWB      |  0  1  1 0 1 0 0
  9. SWB      |  0  1  1 0 0 1 0
  10. SWB      |  0  1  1 1 0 0 1



SWA es un valor casi fijo, se leen ciertos parametros una vez y se genera ese valor.
SWB es un valor dinamico, constantemente esta cambiando y aqui muestro algunos de sus valores y de aqui surge mi pregunta:


1. ¿Como genero esa "cadena" binaria? Pense en esto:




delphi
  1. type boolNum is array[7] of boolean;
  2. SWA : boolNum;
  3. SWB: boolNUm;




Asi puedo escribir el elemento correspondiente en el array segun mis necesidades.


2. ¿Como convierto los elementos de ese array en la representacion de un string binario "0110010"? -¿eso existe?


3. Una vez convertido debo representarlo como un ASCII, p.e. 23, 48, etc  ¿Como hago eso sin delphi?


Help!!!


Se agradece cualquier ayuda!
  • 0

#2 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 04 agosto 2011 - 04:35

Hola amigo Fidel

No entiendo, ¿ podrías ser mas específico con tu planteamiento ?

Como recibes esos datos, es un archivo, es una cadena de caracteres por puerto serial ?

Como quieres que se muestre ese ejemplo que pones en ASCII ????


[tt]
POSICION |  7  6  5 4 3 2 1 |

VALOR    | 64 32 16 8 4 2 1 |
-----------------------------
SWA        0  1  0 1 0 0 1
-----------------------------
SWB      |  0  1  1 0 0 0 0
SWB      |  0  1  1 1 0 0 0
SWB      |  0  1  1 0 1 0 0
SWB      |  0  1  1 0 0 1 0
SWB      |  0  1  1 1 0 0 1
[/tt]

Salud OS
  • 0

#3 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 05 agosto 2011 - 12:13

En delphi se podría hacer, siguiendo tu filosofía, así:



delphi
  1. type boolNum = array[0..6] of boolean;
  2.  
  3. function ABToString(BN: boolNum): String;
  4. var
  5.   i: integer;
  6. begin
  7.   Result:= '';
  8.   for i:=0 to 6 do Result:= Result + IntToStr(integer(BN[i]));
  9. end;


Ejemplo:


delphi
  1.     N[0]:= true;
  2.     N[1]:= false;
  3.     N[2]:= true;
  4.     N[3]:= true;
  5.     N[4]:= true;
  6.     N[5]:= false;
  7.     N[6]:= true;
  8.     Label1.Caption:= ABToString(N);




Saludos.
  • 0

#4 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 05 agosto 2011 - 04:41

vamos a probarlo, ya comentare los resultados.


(b)




  • 0

#5 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 10:26

Siguiendo con tu ejemplo escafandra, tengo esta duda_



for i:=0 to 6 do Result:= Result + IntToStr(integer(BN[i]));

delphi
  1. [size=11px]
  2.  
  3.  
  4. integer es un tipo de dato de delphi, pero aqui que esta haciendo? la ayuda de delphi 2010 no dice mucho.
  5.  
  6.  
  7. por otro lado siguiendo tu ejemplo el resultado mostrado en la etiqueta es:
  8.  
  9.  
  10. [b]1011101[/b]
  11.  
  12. que en decimal equivale a 83 o al caracter ASCII 83.
  13.  
  14.  
  15. Abusando de ti ¿como convierto la cadena binaria en el ascii equivalente?
  16.  
  17.  
  18. Saludos!![/size]





JEJEJE Me respondo con la coversion ascii:

Buscando encontre esta funcion:



delphi
  1. [size=13px]
  2.  
  3. function BinToInt(Value: String): LongInt;
  4. var
  5.   i: Integer;
  6. begin
  7.   Result:=0;
  8. //remove leading zeroes
  9.   while Copy(Value,1,1)='0' do
  10.   Value:=Copy(Value,2,Length(Value)-1) ;
  11. //do the conversion
  12.   for i:=Length(Value) downto 1 do
  13.   if Copy(Value,i,1)='1' then
  14.     Result:=Result+(1 shl (Length(Value)-i)) ;
  15. end;
  16.  
  17. [/size]



  • 0

#6 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 06 agosto 2011 - 11:25

Siguiendo con tu ejemplo escafandra, tengo esta duda_




delphi
  1. for i:= 0 to 6 do Result:= Result + IntToStr(integer(BN[i]));



integer es un tipo de dato de delphi, pero aqui que esta haciendo? la ayuda de delphi 2010 no dice mucho.


IntToStr acepta un entero como parámetro, no un boolean, por eso realizo el cast de boolean a integer: integer(BN)


Saludos.
  • 0

#7 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 12:01

Ok, entendido.


Aquí se me complico la vida por que como dije el lenguaje del aparato esta bastante limitado y la operación de cast no la soporta por lo que debo encontrar otro método de hacer esa conversión.  :(


Tampoco esta soportado el shl  :
  • 0

#8 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 12:20

Ok, entendido.


Aquí se me complico la vida por que como dije el lenguaje del aparato esta bastante limitado y la operación de cast no la soporta por lo que debo encontrar otro método de hacer esa conversión. 


Tampoco esta soportado el shl 


Y si nos comentas con que funciones cuentas, sería más fácil amigo Fidel.

Salud OS
  • 0

#9 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 12:45

:embarrassed:


Buena sugerencia:







Bit-wise Operations


BitAnd
Returns the bit-wise AND result of X and Y.
Method Signature:
function BitAnd (X : Integer; Y : Integer) : Integer;


BitNot
Returns the bit-wise NOT result of X.
Method Signature:
function BitNOT (X : Integer) : Integer;


BitOr
Returns the bit-wise OR result of X and Y.
Method Signature:
function BitOr (X : Integer; Y : Integer) : Integer;


BitXor
Returns the bit-wise exclusive OR (XOR) result of X and Y.
Method Signature:
function BitXor (X : Integer; Y : Integer) : Integer;


String Operations


Asc
Returns the ASCII value of the first character of string S. If S is an empty string, the value returned is 0.
Method Signature:
function Asc (S : String) : Integer;


Chr$
Returns a one-character string containing the ASCII character represented by I.
Method Signature:
function Chr$ (I : Integer) : String;


Hex$
Returns an eight-character hexadecimal string equivalent to I.
Method Signature:
function Hex$ (I : Integer) : String;


LCase$
Returns the string S with all upper-case letters converted to lower case.
Method Signature:
function LCase$ (S : String) : String;


Left$
Returns a string containing the leftmost I characters of string S. If I is greater than the length of S, the function
returns a copy of S.
Method Signature:


function Left$ (S : String; I : Integer) : String;
Len
Returns the length (number of characters) of string S.


Method Signature:
function Len (S : String) : Integer;


Mid$
Returns a number of characters (specified by length) from string s, beginning with the character specified by
start. If start is greater than the string length, the result is an empty string. If start + length is greater
than the length of S, the returned value contains the characters from start through the end of S.


Method Signature:
function Mid$ (S : String; start : Integer; length : Integer) : String;


Oct$
Returns an 11-character octal string equivalent to I.


Method Signature:
function Oct$ (I : Integer) : String;


Right$
Returns a string containing the rightmost I characters of string S. If I is greater than the length of S, the function
returns a copy of S.


Method Signature:
function Right$ (S : String; I : Integer) : String;


Space$
Returns a string containing N spaces.


Method Signature:
function Space$ (N : Integer) : String;


StringSpaceCompress
For large programs that make heavy use of strings, StringSpaceCompress can be used to clean up stored or
non-stored string space.


Method Signature:
function StringSpaceCompress (region : String) : SysCode;


Example:
myString : String;
myStoredString :  stored string;

function StringSpaceCompress (myString); -- Cleans up non-stored string space
function StringSpaceCompress (myStoredString); -- Cleans up stored string space


UCase$
Returns the string S with all lower-case letters converted to upper case.


Method Signature:
function UCase$ (S : String) : String;




Data Conversion


IntegerToString
Returns a string representation of the integer I with a minimum length of W. If W is less than zero, zero is used as
the minimum length. If W is greater than 100, 100 is used as the minimum length.


Method Signature:
function IntegerToString (I : Integer; W : Integer) : String;


RealToString
Returns a string representation of the real number R with a minimum length of W, with P digits to the right of the
decimal point. If W is less than zero, zero is used as the minimum length; if W is greater than 100, 100 is used as
the minimum length. If P is less than zero, zero is used as the precision; if P is greater than 20, 20 is used.


Method Signature:
function RealToString (R : Real; W : Integer; P: Integer) : String;


StringToInteger
Returns the integer equivalent of the numeric string S. If S is not a valid string, the function returns the value 0.


Method Signature:
function StringToInteger (S : String) : Integer;


StringToReal
Returns the real number equivalent of the numeric string S. If S is not a valid string, the function returns the
value 0.0.


Method Signature:
function StringToReal (S : String) : Real;




Por cierto es mi Chrome o a todos las etiquetas salen en orden inverso: cierre al principio y apertura al final.
  • 0

#10 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 06 agosto 2011 - 02:08

¿Puedes hacer un array de boolean?
¿La función IntegerToString acepta un boolean como parámetro?, en ese caso no te hace falta un cast.
¿Que funciones matemáticas soporta, soporta potencias?


Por cierto es mi Chrome o a todos las etiquetas salen en orden inverso: cierre al principio y apertura al final.

A mi me pasa en ocasiones, también introduce un retorno de línea de mas por cada uno verdadero, así como, etiquetas de color, tipo de letra y tamaño de texto cuando le apetece...
...Pero sólo en nuestro foro :( , en los otros funciona bien.


Saludos.
  • 0

#11 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 02:14

1. Si:




delphi
  1. type TboolNum is array[7] of boolean;




2. No:




delphi
  1. function ABToString(BN: TboolNum): string;
  2.   i: integer;
  3.   str:string;
  4.   j:integer;
  5. begin
  6.   str := "";
  7.   for i:=0 to 6
  8.     loop
  9.       str := str + IntegerToString(BN[i]);
  10.     end loop;
  11.   return str;   
  12. end;[/i]




el compilador responde:


Parameter type mismatch




Gracias por el interes!




P.D.
La implementacion del tipo booleano es:



delphi
  1. type boolean is (FALSE, TRUE);




  • 0

#12 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 06 agosto 2011 - 02:46

Puedes tratar de usar una variable entera intermedia para ver si el compilador fuerza el cast:



delphi
  1. function ABToString(BN: TboolNum): string;
  2.   i: integer;
  3.   str:string;
  4.   j:integer;
  5. begin
  6.   str := "";
  7.   for i:=0 to 6
  8.     loop
  9.       j:= BN[i]; // A ver si esto no te da error...
  10.       str := str + IntegerToString(j);
  11.     end loop;
  12.   return str;   
  13. end;



Si no funciona debes trabajar con un array de enteros en lugar de boolean.

No respondiste si soporta funciones matemáticas con potencias, en caso contrario deverás simular las potencias de 2 (hechas en delphi con dsplazamientos shl):



delphi
  1. function _shl(Value, Despl: integer): integer;
  2. var
  3.   i: integer;
  4. begin
  5.   for i:=1 to Despl do
  6.     Value:= Value * 2;
  7.   return:= Value;
  8. end;



Para convertir el valor binario desde el array a un integer no es necesario que pases a convertirlo a string y de quí a integer, puedes hacerlo directamente.

Saludos.
  • 0

#13 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 03:08

Ya me compilo la funcion de :




delphi
  1. [font=dejavu sans mono][/font]
  2. [color=#000080]
  3. function ABToString(BN: TboolNum): string;
  4.   i: integer;
  5.   str:string;
  6.   j:integer;
  7. begin
  8.   str := "";
  9.   for i:=0 to 6
  10.     loop
  11.       --j := BN[i];
  12.       str := str + IntegerToString(BN,7);
  13.     end loop;
  14.   return str;   
  15. end;[/i][/color]
  16. //Este es codigo de prueba para la llamada
  17.  
  18.  
  19.  
  20. handler User1KeyPressed;
  21. begin
  22.   SWB[6] :=  0;
  23.   SWB[5] :=  1;
  24.   SWB[4] :=  1;
  25.   SWB[3] :=  0;
  26.   SWB[2] :=  0;
  27.   SWB[1] :=  0;
  28.   SWB[0] :=  0;
  29.  
  30.   DisplayStatus(ABToString(SWB));
  31. end;




Con respecto a lo de las funciones matematicas si tengo la de potencias:




delphi
  1. function Power (rNumber : real; iPower : integer) : real;





  • 0

#14 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 06 agosto 2011 - 03:16


[code=delphi:0]

type TboolNum is array[7] of integer;

function ABToString(BN: TboolNum): string;[pre]  i: [/size]integer;
 
[/size]str:[/size]string;
 
[/size]begin
 
[/size]str := "";
 
[/size]for i:=[/size]0to6
    loop
     
[/size]str := [/size]str + IntegerToString[/size](BN,7);
   
end loop;
  return
[/size]str;   
[/pre]
[/size]end;[size=1em]
[/d]



Pues si que te ha jugado una mala pasada  :o .


Edita tu código con el botón de abajo a la derecha...


Saludos.
  • 0

#15 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 06 agosto 2011 - 03:21



delphi
  1. function ABToString(BN: TboolNum): string;
  2.   i: integer;
  3.   str:string;
  4.   j:integer;
  5. begin
  6.   str := "";
  7.   for i:=0 to 6
  8.     loop
  9.       --j := BN[i];
  10.       str := str + IntegerToString(BN,7);
  11.     end loop;
  12.   return str;   
  13. end;



Creo que lo publicaste con algún error
"--j" ¿no debe ser "j"?
IntegerToString(BN,7); ¿no debe ser IntegerToString(j,7);?

Saludos.
  • 0

#16 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 04:00

Por estar editando las etiquetas no elimine esa linea. los .. al inicio son comentarios. Si hago eso el compilador protesta.
  • 0

#17 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 06 agosto 2011 - 08:30

Hola amigos,

Hay un problema con las etiquetas, en la semana las revisaremos.

Mientras se resuelve, les sugiero que eviten utilizar la variable 'i'  cuando utilizan el for ya que el índice [nobbc][i][/nobbc] es la etiqueta del tipo de letra itálica. Siento las molestias que esto ocasiona.  :embarrassed:

Salud OS
  • 0

#18 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 07 agosto 2011 - 06:42

:sad:


He estado todo el domingo (bueno no todo pero si bastante) tratando de encontrar cual es el error en la función _shl pues no me da el resultado correcto como si lo hace shl. Anexo el programita con el que he estado probando, tal vez sea una tontería pero .... no la encuentro  :


"La naturaleza del cielo originalmente es clara, a fuerza de mirarlo la vista se oscurece"
  • 0

#19 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 07 agosto 2011 - 07:41

Hola

Si puedes utilizar la función case yo haría esto en la función _shl



delphi
  1. function tForm1._shl(Value:integer): integer;
  2. begin
  3.   case value of
  4.     7 : result := 1;
  5.     6 : result := 2;
  6.     5 : result := 4;
  7.     4 : result := 8;
  8.     3 : result := 16;
  9.     2 : result := 32;
  10.     1 : result := 64;
  11.   end;
  12. end;



Y si no; con unos simples if.



delphi
  1. function tForm1._shl(Value:integer): integer;
  2. begin
  3.     if value = 7 then result := 1;
  4.     if value = 6 then result := 2;
  5.     if value = 5 then result := 4;
  6.     if value = 4 then result := 8;
  7.     if value = 3 then result := 16;
  8.     if value = 2 then result := 32;
  9.     if value = 1 then result := 64;
  10.   end;
  11. end;



Y la función BitToInt la dejo así.



delphi
  1. function TForm1.BinToInt(Value: String): LongInt;
  2. var
  3.   j: Integer;
  4. begin
  5.   Result:=0;
  6.  
  7.   for j := 1 to length(value) do
  8.     if Copy(Value,j,1)='1' then
  9.     begin
  10.       Memo1.lines.add(IntToStr(_shl(j)));
  11.       Result := Result + _shl(j);
  12.     end;
  13. end;



Salud OS
  • 0

#20 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.446 mensajes
  • LocationMéxico

Escrito 07 agosto 2011 - 10:06

Modifiqué tu programa un poco.



delphi
  1. unit Unit1;
  2.  
  3. interface
  4.  
  5. uses
  6.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  7.   Math, Dialogs, StdCtrls;
  8.  
  9. type TboolNum = array[1..7] of integer;
  10.  
  11. type
  12.   TForm1 = class(TForm)
  13.     Label1: TLabel;
  14.     Button1: TButton;
  15.     Label2: TLabel;
  16.     Memo1: TMemo;
  17.     Memo2: TMemo;
  18.     procedure Button1Click(Sender: TObject);
  19.   private
  20.     { Private declarations }
  21.     N: TboolNum;
  22.     function _shl(Value:integer; Despl: integer): integer;
  23.     function BinToInt(Value: TboolNum): LongInt; //Usamos directo el arreglo TboolNum
  24.   public
  25.     { Public declarations }
  26.   end;
  27.  
  28. var
  29.   Form1: TForm1;
  30.  
  31. implementation
  32.  
  33. {$R *.dfm}
  34.  
  35. {Esta funcion convierte el array de enteros a una cadena}
  36. function ABToString(BN: TboolNum): String;
  37. var
  38.   j: integer;
  39. begin
  40.   Result:= '';
  41.   for j := 7 downto 1  do
  42.     Result:= Result + IntToStr((BN[j]));
  43. end;
  44.  
  45. function tForm1._shl(Value, Despl: integer): integer;
  46. var
  47.   j: integer;
  48. begin
  49.   for j := 1 to Despl do
  50.   begin
  51.     Value:= Value * 2;
  52.     Memo2.Lines.Add(floattostr(Value));
  53.   end;
  54.   result := Value;
  55. end;
  56.  
  57. {Esta funcion convierte la cadena que representa el valor booleano en un entero}
  58. function TForm1.BinToInt(Value: TboolNum): LongInt;
  59. var
  60.   j: Integer;
  61. begin
  62.   Result:=0;
  63.   for j := Length(Value) downto 1 do
  64.   if Value[j] = 1 then
  65.   begin
  66.     Memo1.lines.add(IntToStr(_shl(1,j-1)));
  67.     Result := Result + _shl(1,j-1) ;
  68.   end;
  69. end;
  70.  
  71. procedure TForm1.Button1Click(Sender: TObject);
  72. begin
  73.   N[1]:= 0; //Usamos base 1 y no base 0 como lo tenias
  74.   N[2]:= 0;
  75.   N[3]:= 0;
  76.   N[4]:= 0;
  77.   N[5]:= 1;
  78.   N[6]:= 1;  // 64 32 16  8  4  2  1
  79.   N[7]:= 0;  //  0  1  1  0  0  0  0 = 48
  80.  
  81.   Label1.Caption:= ABToString(N);
  82.   Label2.Caption := IntToStr(BinToInt(N)); //Usamos directamente el arreglo, sin la función ABToString()
  83. end;
  84.  
  85. end.



Salud OS

  • 0




IP.Board spam blocked by CleanTalk.