📄 cstring.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
namespace SMPP.Variable
{
/// <summary>
/// 定长字符串类型
/// 有两种可能的长度:一个字节的0x00(即空字符串)或固定长度的以NULL结尾的字符串
/// </summary>
public class CString : Variable
{
/// <summary>
/// 保存的真实数据
/// </summary>
protected byte[] _Value = new byte[1];
private int FixedLength = 1;
public override int Length
{
get
{
return _Value.Length;
}
}
private System.Text.Encoding Encoding = System.Text.Encoding.ASCII;
public string Value
{
get
{
if (_Value.Length == 0)
return "";
else
{
return Encoding.GetString(_Value, 0, Array.IndexOf(_Value, (byte)0));
}
}
set
{
if (value == null || value == "" || Encoding.GetByteCount(value) != FixedLength - 1)
{//如果值为空或者空字符串,或者长度不能匹配到固定长度(FixedLength - 1是为了留出最后一个字节的NULL空间)
_Value = new byte[1];
_Value[0] = 0;
}
else
{
_Value = new byte[FixedLength];
byte[] data = Encoding.GetBytes(value);
Array.Clear(_Value, 0, FixedLength);
Array.Copy(data, _Value, data.Length);
}
}
}
public override void Parse(byte[] Datas, ref int Index)
{
int index = Array.IndexOf(Datas, (byte)0, Index);
if (index == -1)
throw new Exception("没有找到以NULL结尾的串");
if (index - Index == 0)
{
Value = "";
Index++;
}
else
{
if (index - Index != FixedLength - 1)
throw new Exception("串长度不正确");
_Value = new byte[FixedLength];
Array.Copy(Datas, Index, _Value, 0, FixedLength);
Index = index + 1;
}
}
public override byte[] GetBytes()
{
byte[] ret = new byte[_Value.Length];
Array.Copy(_Value, ret, ret.Length);
return ret;
}
public CString(int Length)
{
FixedLength = Length;
}
public CString(int Length, System.Text.Encoding Encoding)
{
FixedLength = Length;
this.Encoding = Encoding;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -