我是一個初學者愛好者,並且一直在我的代碼中研究一個問題。我的代碼很醜陋,效率很低,主要是因爲我缺乏經驗。不過,我喜歡這個東西。給定一個字符串轉換爲4字節塊的十六進制... C#
問題:給出一個字符串,我可以成功轉換爲十六進制。然而,我希望給定的字符串(儘管它的長度)被轉換爲十六進制的4字節塊。對於字符串大於一個字節但小於4個字節的情況,我想在字符串的右側填充「0」。我發現只有部分成功,只要我操作PadRight方法的totalWidth參數即可。我怎樣才能達到我所追求的目標,而不需要額外的零碎塊?
請看到確切的代碼示例我使用下面:
// create a char array using the string provided to the encoder method
char[] arrayCharValues = strMessage.ToCharArray();
// create stringbuilder object
StringBuilder sb = new StringBuilder();
// iterate through each char and convert it to int32 then to Hex then append to stringbuilder object.
foreach (char c in arrayCharValues)
{
// convert char to int32
int intCharToNumVal = Convert.ToInt32(c);
// convert int32 to hex
string strNumToHexVal = String.Format("{0:X2}", intCharToNumVal);
// append hex value to string builder object
sb.Append(strNumToHexVal);
}
string s = sb.ToString();
if (s.Length % 8 == 0)
{
var list = Enumerable
.Range(0, s.Length/8)
.Select(i => s.Substring(i * 8, 8))
.ToList();
var res = string.Join(" ", list);
// DEBUG: echo results for testing.
Console.WriteLine("");
Console.WriteLine("String provided: {0}", strMessage);
Console.WriteLine("String provided total length: {0}", s.Length);
Console.WriteLine("Hex equivalent of string provided: {0}", sb.ToString());
Console.WriteLine("Hex in 8-digit chunks: {0}", res.ToString());
Console.WriteLine("======================================================");
}
else
{
int intDivisibleByEight = s.Length % 8;
int intPadRight = (8 - intDivisibleByEight)/2;
char pad = '0';
//BUG: doesn't know how to handle anything over 16 bits. If I use an input string of "coolsssss" i get 636F6F6C 73737373 73000000 00000000
//BUG: <cont'd> if i use the same input string and change the PadRight(32,pad) to PadRight(16,pad) i get 636F6F6C 73737373 and the final chunk is ignored.
//BUG: <cont'd> I want it to work as it does with the PadRight(32, pad) method but, I want it to ignore the all zeros chunk(s) that may follow.
//NOTE: int totalWidth = the number of characters i nthe resulting string, equal to the number of original characters plus any additional padding characters.
s = s.PadRight(32, pad);
var list = Enumerable
.Range(0, s.Length/8)
.Select(i => s.Substring(i * 8, 8))
.ToList();
var res = string.Join(" ", list);
// DEBUG: echo results for testing.
Console.WriteLine("");
Console.WriteLine("String provided: {0}", strMessage);
Console.WriteLine("String provided total length: {0}", s.Length);
Console.WriteLine("Hex equivalent of string provided: {0}", sb.ToString());
Console.WriteLine("Hex in 8-digit chunks: {0}", res.ToString());
Console.WriteLine("======================================================");
}
爲什麼不在你轉換之前填充你的輸入字符串?然後你的轉換器函數可以假設所有的字符串都是(例如8)的倍數,你不必擔心類似的代碼分割。 –
感謝您的提示。我會嘗試以下提供的示例。 –