jueves, 24 de octubre de 2013

Funciones de Conversion (VB.NET--C#)

Que tal buen dia en esta ocasion les voy a mostrar algunas funciones para convertir numeros binarios a hexadecimal , ascii a hexadecimal y algunas mas, que se van a utilizar en la siguiente entrada donde les voy a enseñar como manipular un dispositivo serial jeje , sin mas preambulos vamos a las funciones:

Primeramente crear un formulario como el siguiente :


1.- 2 Textbox(Texto Original y Texto Convertido).
2.- 2 Etiquetas(Texto Original y Texto Convertido).
3.- 5 Botones().

Una vez que se tiene el formulario empezamos con las funciones.


Funcion para Convertir ASCII a Hexadecimal .

Codigo VB.


Function asc2hex(ByVal StrName As String) As String
        Dim cont As Integer = 0
        Dim strAcum As String = ""
        For cont = 1 To Len(StrName)
            strAcum &= Hex(Asc(Mid(StrName, cont, 1)))
        Next cont
        Return strAcum
    End Function
Codigo C#
public string asc2hex(string StrName)
{
	int cont = 0;
	string strAcum = "";
	for (cont = 1; cont <= Strings.Len(StrName); cont++) {
		strAcum += Conversion.Hex(Strings.Asc(Strings.Mid(StrName, cont, 1)));
	}
	return strAcum;
}


Funcion Para convertir Hexadecimal a Binario. 

Codigo VB.

Public Function hexbi(ByVal hex As String) As Long
        Dim bin As String = ""
        bin = Convert.ToString(Convert.ToInt32(hex, 16), 2)
        Return bin
    End Function

Codigo C #
public long hexbi(string hex)
{
	string bin = "";
	bin = Convert.ToString(Convert.ToInt32(hex, 16), 2);
	return bin;
}

Funcion Para Convertir Ascii a Hexadecimal.

Codigo VB.

Public Function asciiaHex(ByVal ascci As String) As ArrayList
        Dim arr As New ArrayList
        Dim sBufer As StringBuilder = New StringBuilder
        Dim i As Integer
        For i = 0 To ascci.Length - 1
            sBufer.Append(Convert.ToInt32(ascci(i)).ToString("x"))
            arr.Add(Convert.ToInt32(ascci(i)).ToString("x"))
        Next
        Return arr
    End Function
Codigo C#.


public ArrayList asciiaHex(string ascci)
{
	ArrayList arr = new ArrayList();
	StringBuilder sBufer = new StringBuilder();
	int i = 0;
	for (i = 0; i <= ascci.Length - 1; i++) {
		sBufer.Append(Convert.ToInt32(ascci[i]).ToString("x"));
		arr.Add(Convert.ToInt32(ascci[i]).ToString("x"));
	}
	return arr;
}
Funcion que convierte un arreglo de bytes en Hexadecimal.

Codigo VB.

Public Function ByteToHex(ByVal comByte As Byte()) As String
        'Creamos un objeto stringBuilder
        Dim builder As New StringBuilder(comByte.Length * 3)
        'Recorrer Cada Byte de la matriz
        For Each data As Byte In comByte
            If data <> 0 Then
                builder.Append(Convert.ToString(data, 16).PadLeft(2, "0"c).PadRight(3, " "c))
                'Convertir el byte a string y agregar a el stringbuilder
            End If
        Next
        'Regresamos el valor convertido
        Return builder.ToString().ToUpper()
    End Function
Codigo C#.


public string ByteToHex(byte[] comByte)
{
	//Creamos un objeto stringBuilder
	StringBuilder builder = new StringBuilder(comByte.Length * 3);
	//Recorrer Cada Byte de la matriz
	foreach (byte data in comByte) {
		if (data != 0) {
			builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
			//Convertir el byte a string y agregar a el stringbuilder
		}
	}
	//Regresamos el valor convertido
	return builder.ToString().ToUpper();
}
Estas cuatro funciones son muy importantes , cuando trabajamos con dispositivos seriales en el siguiente post les enseñare como comente arriba, como manipular un billetero por el puerto serial.

Les dejo el codigo fuente en el siguiente link:

 FuncionesConversion.rar (74 KB) https://mega.co.nz/#!5YpzwSjD!f2wJJQo1mKZp4Zct5zCwIwCNJLBO9DnPJ8RMmoCUM-8

Saludos.

 cualquier duda por aqui andamos.

2 comentarios:

  1. Estimado, y las conversiones en viceversa las tiene....? más me intereza convertir de Hexadecimal a bytes() en VB.Net

    ResponderEliminar
  2. Claro usando linq tengo esta function.

    Public Shared Function Hex ToByteArray(hex As String) As Byte()
    Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
    End Function

    ResponderEliminar

Hola Deja Tu Comentario !!!