问题
I have an integer that gets incremented
I then want this in hex so I do the conversion like so: myInt.ToString("X");
I then need a string in the format of 00 00 00 00 but I cannot work out a way to convert the hex string I now have into this format.
回答1:
With a Linq query you can do this:
string.Join(" ", BitConverter.GetBytes(myInt).Select(x=>x.ToString("x")).ToArray());
回答2:
Fun Mode On Part 1
I can use Regexes for replace! Wozza!!!
string str = Regex.Replace(
String.Format("{0:X8}", myVal),
"([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})",
"$1 $2 $3 $4"
);
I'm writing the number in 8 digits hex format with the String.Format and then I'm inserting the spaces using a Regex. Yes, it's overkill and useless :-)
Seriously
string str = String.Format(
"{0:X2} {1:X2} {2:X2} {3:X2}",
(myVal >> 24) & 0xFF,
(myVal >> 16) & 0xFF,
(myVal >> 8) & 0xFF,
myVal & 0xFF);
Taking a piece at a time using shifts and an "&& Mask" and composing them using String.Format in Hex formatting with padding 2.
Don't use them with negative numbers, please!
Fun Mode On Part 2 (The Return of the Angry Regex)
string str = Regex.Replace(
String.Format("{0:X8}", myVal),
"([0-9A-F]{2})(?!$)",
"$1 "
);
Here we search for groups of 2 Hex digits that aren't at the end of the string and add a space after them (We could have used \B (remember to escape) instead of (?!$))
回答3:
You can specify the number of hex digits using a number after the 'x' (e.g. 'x2'). A lower-case 'x' will give you lower-case hex, and visa-versa with an upper-case one.
The following methods will the the least wasteful you will find:
/// <summary>
/// Converts the specified byte array into a delimited list of hex pairs.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="requiredLength">The required length (in bytes) required.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>The binary value.</returns>
static string ToBinaryString(byte[] values, int requiredLength, string delimiter, bool allowLonger)
{
if (values == null)
return null;
if (values.Length > requiredLength)
{
if (allowLonger)
requiredLength = values.Length;
else
throw new ArgumentOutOfRangeException("values");
}
// Create the StringBuilder with the precise length of values.
var sb = new StringBuilder((2 + delimiter.Length) * requiredLength - delimiter.Length);
var padLength = requiredLength - values.Length;
for (var i = 0; i < padLength; i++)
sb.Append(sb.Length == 0 ? "" : delimiter)
.Append("00");
for (var i = 0; i < values.Length; i++)
sb.Append(sb.Length == 0 ? "" : delimiter)
.Append(values[i].ToString("x2"));
return sb.ToString();
}
/// <summary>
/// Converts the specified byte array into a delimited list of hex pairs.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>
/// The binary value.
/// </returns>
static string ToBinaryString(byte[] values, string delimiter)
{
return ToBinaryString(values, 0, delimiter, true);
}
EDIT: If you have an Int32 the following would work without unessecary allocations:
/// <summary>
/// Converts the specified <see cref="Int32"/> into a delimited list of hex pairs.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>The binary value.</returns>
static string ToBinaryString(int value, string delimeter)
{
var u = (uint)IPAddress.HostToNetworkOrder(value);
var sb = new StringBuilder((2 + delimeter.Length) * 4 - delimeter.Length);
sb.Append(((u >> 0) & 0xFF).ToString("x2")).Append(delimeter);
sb.Append(((u >> 8) & 0xFF).ToString("x2")).Append(delimeter);
sb.Append(((u >> 16) & 0xFF).ToString("x2")).Append(delimeter);
sb.Append(((u >> 24) & 0xFF).ToString("x2"));
return sb.ToString();
}
来源:https://stackoverflow.com/questions/7310697/convert-int-to-hex-and-then-into-a-format-of-00-00-00-00