字符串到字节?转换 [英] string to byte ? conversion

查看:144
本文介绍了字符串到字节?转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将命令发送到计算机

机器接受带有字节数组的数据包...

我需要构建一个表单,该表单将允许用户以char格式输入命令,然后将其转换为字节数组,例如

我可以寄机器

I am trying to send commands to a machine

The machine accepts the packet with a byte array...

I need to build a form that will allow the user to enter the command in char format and then convert it to a byte array for example

I can send the machine

byte[] packet = 
{
((byte) (0x02)),
((byte) (0x05)),
((byte) (0xFF)),

};



我需要用户能够输入例如"0x02 0x07 0x03 0xFF"
并将来自textbox.text的字符串转换为一个字节数组,该数组具有代表ansi格式的4个字节值

我尝试失败了:



I need the user to be able to input for example "0x02 0x07 0x03 0xFF"
and the string from the textbox.text be converted into a byte array with the for 4 byte values that represent the ansi format

I tried without success:

byte[] packet =
{
((byte) (string1)),
((byte) (string2)),
((byte) (string3)),



OP的答案移至此处:
试图用谷歌搜索它,令人沮丧的是我找不到任何东西.
如果我使用上面链接中的代码,它将使用值解释每个数字和字母
对于下面的示例,字节数组有14个项目.我需要获取3个值.我可能会用空格来分隔字符串,然后获取每个字符串的值
在这种情况下
0x02 = 2
0xFF = 255
0x03 = 3
或者我可以获取字符串并将文字字符串"0x02"转换为带有其字节值的字节数组的方法

System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte [] myByteArray = enc.GetBytes("0x02 0xFF 0x03");



OP''s Answer moved to here:
tried to google it already and frustrating that I can''t find anything.
if I use the code from the above link, it interprets each digit and letter with a value
for the example below the byte array had 14 items. I need to get the 3 values. I would probably deliminate the string by spaces and then get the values for each one
In this case
0x02= 2
0xFF = 255
0x03 = 3
or a way that I can get the string and convert the literal string "0x02" and add it to to a byte array with its byte value

System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] myByteArray = enc.GetBytes("0x02 0xFF 0x03");

推荐答案

结帐:
1- String.Split方法(Char []) [ Byte.Parse方法(字符串,NumberStyles) [ System.BitConverter [
Checkout:
1- String.Split Method (Char[])[^]
2- Byte.Parse Method (String, NumberStyles)[^] (System.Globalization.NumberStyles.HexNumber for instance for Hex parsing)
3- For further practice System.BitConverter[^] which seems redundant for question but maybe usefull if you are going to use byte stuff.


This should work for you: (2nd argument of ToByte is base of converted number)
string input = "0x02 0x07 0x03 0xFF";
            return input.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();


http://geekswithblogs.net/TimH/archive/2005/06/27/44849.aspx [ ^ ]

Google是免费的,随时可供您使用.
http://geekswithblogs.net/TimH/archive/2005/06/27/44849.aspx[^]

Google is free, and ready for you to use.


这篇关于字符串到字节?转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆