简体   繁体   English

字节到字符串“小数点是个问题”

[英]byte to string “decimal point is a problem”

This code is written in C# dot net 这段代码是用C#点网编写的

i am receiving DATA in below mention format 49 46 48 50 which is equivalent to 1.02 in decimal format using this simple code 我正在接收以下提到的格式49 46 48 50的数据,使用此简单代码相当于十进制格式的1.02

DATA = Convert.ToByte(serialPort1.ReadByte());

later i add DATA in a buffer 后来我在缓冲区中添加数据

buffer[byte_count++] = DATA;   // byte[] buffer = new byte[256];

Now with 49 46 48 50 DATA byte value 现在具有49 46 48 50 DATA字节值

buffer[1] contains 49
buffer[2] contains 46
buffer[3] contains 48
buffer[4] contains 50

problem is the decimal point i can convert 49 to 1 by simple subtracting byte value from 48 but how could i convert 46 into the decimal point and save all bytes into an strings 问题是小数点,我可以通过简单地从48中减去字节值将49转换为1,但是我怎么能将46转换为小数点并将所有字节保存为字符串

really very appreciate if any one can solve my problem Ashraf 非常感谢有人能解决我的问题

Assuming the data is ASCII use (UPDATE as per comment): 假设数据使用ASCII码(根据注释更新):

string MyString = Encoding.ASCII.GetString (buffer, 1, 4);

MSDN reference see http://msdn.microsoft.com/de-de/library/system.text.encoding.aspx MSDN参考请参阅http://msdn.microsoft.com/de-de/library/system.text.encoding.aspx

Use the Encoding class: 使用Encoding类:

string value = Encoding.ASCII.GetString(buffer, 1, 4);

Note: You have placed the data in the array starting from 1, but array indexes are zero based, so you need to specify the offset and length in the GetString call. 注意:您已将数据从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM