日期:2014-05-18  浏览次数:20862 次

求救,Socket.Send发送十六进制数的问题
System.Byte[] message = System.Text.Encoding.Default.GetBytes(msg.ToCharArray());
clientSocket.Send(message, message.Length, 0);

正如上面代码:msg是要发送的字符串,但我要把这个字符串以十六进制的方式发送出去。因为客户是以十六进制接受的,上面的代码不能实现!
向高手求救!怎么样才能把一行字符串以十六进制通过Socket以送出去?
比如:msg="00 AC 10 01";

------解决方案--------------------
其实你需要两个转换过程:
1:由字符串得到字节流,这个你已经实现了。
2:把字节流转换为相应的16进制字节流。
看看这一段代码:
C# code

System.Convert.ToString('a',16);//   ==>输出   61   
  byte[]   btArr   =   new   byte[]{97,98,99,100};   
  System.BitConvert.ToString(btArr);//   ==>输出   61-62-63-64

------解决方案--------------------
MSDN上的一段代码,相当漂亮:
C# code

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
/* Output:
   Hexadecimal value of H is 48
    Hexadecimal value of e is 65
    Hexadecimal value of l is 6C
    Hexadecimal value of l is 6C
    Hexadecimal value of o is 6F
    Hexadecimal value of   is 20
    Hexadecimal value of W is 57
    Hexadecimal value of o is 6F
    Hexadecimal value of r is 72
    Hexadecimal value of l is 6C
    Hexadecimal value of d is 64
    Hexadecimal value of ! is 21
 */