[英]byte to string “decimal point is a problem”
这段代码是用C#点网编写的
我正在接收以下提到的格式49 46 48 50的数据,使用此简单代码相当于十进制格式的1.02
DATA = Convert.ToByte(serialPort1.ReadByte());
后来我在缓冲区中添加数据
buffer[byte_count++] = DATA; // byte[] buffer = new byte[256];
现在具有49 46 48 50 DATA字节值
buffer[1] contains 49
buffer[2] contains 46
buffer[3] contains 48
buffer[4] contains 50
问题是小数点,我可以通过简单地从48中减去字节值将49转换为1,但是我怎么能将46转换为小数点并将所有字节保存为字符串
非常感谢有人能解决我的问题
假设数据使用ASCII码(根据注释更新):
string MyString = Encoding.ASCII.GetString (buffer, 1, 4);
MSDN参考请参阅http://msdn.microsoft.com/de-de/library/system.text.encoding.aspx
使用Encoding
类:
string value = Encoding.ASCII.GetString(buffer, 1, 4);
注意:您已将数据从1开始放置在数组中,但是数组索引从零开始,因此您需要在GetString
调用中指定偏移量和长度。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = { 49, 46, 48, 50 };
//get string
string str = new string(Encoding.ASCII.GetChars(bytes));
Console.WriteLine(str);
//get number
double d;
if (double.TryParse(str, out d))
{
Console.WriteLine(d);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.