[英]Converting from string to byte
我有一個40FA
的字符串。 我想對其執行XOR操作,並在這種情況下返回一個0xBA
字節。 但是,我只能以字符串形式獲取該BA
。 當我將BA
轉換為byte時,我得到186
。
string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);
int test = uid_1 ^ uid_2 ;
string final = test.ToString("X");
byte byteresult = Byte.Parse(final , NumberStyles.HexNumber);
嘗試:
byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
and for bytes to string
string something = Encoding.ASCII.GetString(toBytes);
嘗試調用該函數,它將string
轉換為bytes
private byte[] String_To_Bytes2(string strInput)
{
int numBytes = (strInput.Length) / 2;
byte[] bytes = new byte[numBytes];
for (int x = 0; x < numBytes; ++x)
{
bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
}
return bytes;
}
static void Main(string[] args)
{
string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);
int test = uid_1 ^ uid_2;
string final = test.ToString("X");
byte[] toBytes = String_To_Bytes2(final);
Console.WriteLine(toBytes);
Console.ReadKey();
}
您的輸入似乎是十六進制值,因此您需要將兩位數字解析為一個字節。 然后對這兩個字節進行XOR。
結果是十進制的186
或十六進制的BA
。 它是相同的值,只是另一個基數。
string tmp = "40FA";
byte uid_1 = byte.Parse(tmp.Substring(0, 2), NumberStyles.HexNumber);
byte uid_2 = byte.Parse(tmp.Substring(2, 2), NumberStyles.HexNumber);
byte test = (byte)(uid_1 ^ uid_2); // = 186 (decimal) = BA (hexadecimal)
string result = test.ToString("X");
我認為這里有些誤解。 您實際上已經解決了您的問題。 計算機不在乎該數字是十進制還是十六進制,八進制或二進制。 這些只是數字的表示。 因此,只有您關心它的顯示方式。
正如DmitryBychenko已經說過的:0xBA與186相同。如果要在其中存儲字節數組,則與字節數組無關。 僅當您要顯示時才對您重要。
編輯:您可以通過運行以下代碼行對其進行測試:
Console.WriteLine((byteresult == Convert.ToInt32("BA", 16)).ToString());
如果我從您的注釋中正確理解了您的代碼,則您的代碼實際上會執行您想要的操作。
string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);
int test = uid_1 ^ uid_2 ;
string final = test.ToString("X");
// here you actually have achieved what you wanted.
byte byteresult = Byte.Parse(final , NumberStyles.HexNumber);
現在,您可以使用byteresult
將其存儲在byte[]
,這是:
byte[] MyByteArray = new byte[4];
MyByteArray [0] = byteresult;
應該執行沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.