[英]Bit convector : Get byte array from string
當我有一個類似“ 0xd8 0xff 0xe0”的字符串時,我會
Text.Split(' ').Select(part => byte.Parse(part, System.Globalization.NumberStyles.HexNumber)).ToArray();
但是,如果我得到類似“ 0xd8ffe0”的字符串,我不知道該怎么辦?
我也可以建議如何將字節數組寫為一個字符串。
開始解析之前,您需要先清理字符串。 首先,刪除前導0x,然后在枚舉字符串時跳過所有空格。 但是為此使用LINQ可能不是最佳方法。 一方面,該代碼不太容易閱讀,並且如果您要調試,則很難單步執行。 而且,您可以采取一些技巧來非常快速地進行十六進制/字節轉換。 例如,不要使用Byte.Parse,而是使用數組索引來“查找”相應的值。
前一段時間,我實現了一個HexEncoding類,該類從Encoding基類派生而來,非常類似於ASCIIEncoding和UTF8Encoding等。使用它非常簡單。 它也進行了很好的優化,這可能非常重要,具體取決於數據的大小。
var enc = new HexEncoding();
byte[] bytes = enc.GetBytes(str); // convert hex string to byte[]
str = enc.GetString(bytes); // convert byte[] to hex string
這是完整的課程,我知道這對於發布來說有點大,但是我已經刪除了文檔注釋。
public sealed class HexEncoding : Encoding
{
public static readonly HexEncoding Hex = new HexEncoding( );
private static readonly char[] HexAlphabet;
private static readonly byte[] HexValues;
static HexEncoding( )
{
HexAlphabet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
HexValues = new byte[255];
for ( int i = 0 ; i < HexValues.Length ; i++ ) {
char c = (char)i;
if ( "0123456789abcdefABCDEF".IndexOf( c ) > -1 ) {
HexValues[i] = System.Convert.ToByte( c.ToString( ), 16 );
} // if
} // for
}
public override string EncodingName
{
get
{
return "Hex";
}
}
public override bool IsSingleByte
{
get
{
return true;
}
}
public override int GetByteCount( char[] chars, int index, int count )
{
return count / 2;
}
public override int GetBytes( char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex )
{
int ci = charIndex;
int bi = byteIndex;
while ( ci < ( charIndex + charCount ) ) {
char c1 = chars[ci++];
char c2 = chars[ci++];
byte b1 = HexValues[(int)c1];
byte b2 = HexValues[(int)c2];
bytes[bi++] = (byte)( b1 << 4 | b2 );
} // while
return charCount / 2;
}
public override int GetCharCount( byte[] bytes, int index, int count )
{
return count * 2;
}
public override int GetChars( byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex )
{
int ci = charIndex;
int bi = byteIndex;
while ( bi < ( byteIndex + byteCount ) ) {
int b1 = bytes[bi] >> 4;
int b2 = bytes[bi++] & 0xF;
char c1 = HexAlphabet[b1];
char c2 = HexAlphabet[b2];
chars[ci++] = c1;
chars[ci++] = c2;
} // while
return byteCount * 2;
}
public override int GetMaxByteCount( int charCount )
{
return charCount / 2;
}
public override int GetMaxCharCount( int byteCount )
{
return byteCount * 2;
}
} // class
十六進制String
到byte[]
:
byte[] bytes = new byte[value.Length / 2]; for (int i = 0; i < value.Length; i += 2) { bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16); }
如果"0x"
為"0x"
,則應跳過兩個字節。
byte[]
或任何IEnumerable<Byte>
->十六進制String
:
return sequence.Aggregate(string.Empty, (result, value) => result + string.Format(CultureInfo.InvariantCulture, "{0:x2}", value));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.