[英]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.