try
{
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
return responseData;
//Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
}
catch (ArgumentNullException e)
{
public class TestAscii {
public static void main(String[] s){
printAsciiHex('a');
printAsciiHex('1');
printHex(1);
printHex(16);
printHex(18);
printHex(255);
}
public static void printAsciiHex(char ch){
int i=(int)ch; //i=a的ASCII
System.out.println(ch + " ascii:" + i);
String str=Integer.toString(i,16); //十六进制
System.out.println(ch + " ascii 的十六进制:" + str);
}
//得到一个数的十六进制形式
public static void printHex(int i){
String str=Integer.toString(i,16); //十六进制
System.out.println(i + "的十六进制:" + str);
}
}
public class StringToHex{
public String convertStringToHex(String str){
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for(int i = 0; i < chars.length; i++){
hex.append(Integer.toHexString((int)chars[i]));
}
return hex.toString();
}
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
return sb.toString();
}
//504F533838383834 POS88884
public static void main(String[] args) {
StringToHex strToHex = new StringToHex();
System.out.println("\n-----ASCII码转换为16进制 -----");
String str = "POS88884";
System.out.println("字符串: " + str);
String hex = strToHex.convertStringToHex(str);
System.out.println("转换为16进制 : " + hex);
System.out.println("\n***** 16进制转换为ASCII *****");
System.out.println("Hex : " + hex);
System.out.println("ASCII : " + strToHex.convertHexToString(hex));
}
}