将文本框中的十六进制值多数民众赞成转换为单个十六进制对 [英] Convert Hex Value thats in a text box to Individual Hex Pairs

查看:79
本文介绍了将文本框中的十六进制值多数民众赞成转换为单个十六进制对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿人们,

我有一个奇怪的问题,我想在文本框中转换一个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?

推荐答案

解决方案1:

Solution 1:

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));



两种解决方案都经过测试.

享受吧!

—SA



Both solutions are tested.

Enjoy!

—SA


为什么不读一次提取两个字符并在其后附加"0x"?

抱歉,放屁了.我认为您除了上面的琐碎回答之外,还想要其他东西.

请参见此处 [
Why not just read extract two characters at a time and append "0x" to it?

Sorry, brain fart. I assume you want something more than this trivial response above.

See here[].


这篇关于将文本框中的十六进制值多数民众赞成转换为单个十六进制对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆