问题描述
嘿人们,
我有一个奇怪的问题,我想在文本框中转换一个Hex值,并获取实际的表示形式以进行传输.例如,假设我在文本框中输入A3D56712,我想以十六进制格式获取0xA3、0xD5、0x67、0x12.
有任何想法吗?
Hey people,
Curious problem I have, I want to convert a Hex value thats in a text box and get the actual representation to transport that. For Example say I enter A3D56712 in the text box, I want to get 0xA3, 0xD5, 0x67, 0x12, in HEX form.
Any Ideas?
推荐答案
static string[] ToHexArray(uint value) {
int len = sizeof(uint);
string[] result = new string[len];
for (int index = 0; index < len; ++index) {
int shift = 8 * (len - index - 1);
uint mask = (uint)byte.MaxValue << shift;
uint masked = value & mask;
result[index] = ((byte)(masked >> shift)).ToString("X");
} //loop
return result;
}
解决方案2:
Solution 2:
static string[] ToHexArray(uint value) {
return System.Array.ConvertAll(
System.BitConverter.GetBytes(value),
new System.Converter<byte, string>(
(src) => {
return src.ToString("X");
}));
}
第一个解决方案将最重要的数字放在左侧(您可以轻松地在代码中对其进行更改),第二个解决方案在右侧(组合语言样式;您无法在算法中对其进行更改,但可以稍后将其反转).您可以使用string.Format
而不是ToString
为每个字符串添加"0x"前缀.您可以使用:
First solution puts most significant figure at left (you can easily change it in code), second one — at right (Assembly language style; you cannot change it in algorithm but can reverse it later). You can add "0x" prefix to each string by using string.Format
instead of ToString
. You can use:
string[] hexArray = ToHexArray(
uint.Parse(
MyTextBox.Text,
System.Globalization.NumberStyles.HexNumber));
两种解决方案都经过测试.
享受吧!
Both solutions are tested.
Enjoy!
这篇关于将文本框中的十六进制值多数民众赞成转换为单个十六进制对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!