silanos_1

Analytics

ad silanors2

2011年3月31日 星期四

[C#]使用 String取Byte從第n位以後n個byte(Use String Byte taken from the n bits after the n-th byte)


問題

使用 String取Byte從第n位以後n個byte



解決方法

常在寫一些資料交換系統的工程師都知道,最常用來交換資料的就是TXT格式,
然而格式大概都是如下:

欄位 位置 長度
NAME 1 20
ID 21 10
AGE 31 2
SEX 33 1
交換格式都採用這種方式,而在取資料的時候,常常會遇到"中文字" 
而一個中文字有2個BYTE的大小,因此若欄位有夾雜中英文的話,常常會取錯資料,因此貢獻出自己的class用來處理! 

此擷取資料的方式很簡單,所見即所得,也就是將文件上的欄位對抄餵給function就可以了!! 
namespace B2c.DataEngine.Core
{
    public class GetChar
    {
        private int totalLenght = 0;
        public GetChar(int TotalLenght)
        {
            //if (TotalLenght == 0)
            //    throw new ArgumentException("Can't be zero");
            totalLenght = TotalLenght;
        }
        /// 
        /// 取得字串,字串,幾位,開始以後幾位
        /// 
        public string Position(string stringLine, int startPosition, int afterNumber)
        {
            byte[] _byte = System.Text.Encoding.Default.GetBytes(stringLine);
            string _string = string.Empty;
            if (_byte.Length >= totalLenght)
            {
                int _sp = startPosition-1;
                int _ep = afterNumber;
                _string = System.Text.Encoding.Default.GetString(_byte, _sp, _ep);
            }
            return _string;
        }
    }
}

1 則留言:

匿名 提到...

Nothing so bad, as not to be good for something.

as silanors3

熱門文章

bloggerads