c#:如何将short型或int型的数据转换成十六进制,单字节间用空格分隔

Chouna 发布于 2012/07/18 23:56
阅读 2K+
收藏 0
C#
如何将short型或int型的数据转换成十六进制,并且单字节间用空格分隔,例如65535-->ff ff
加载中
1
Chouna
Chouna

引用来自“瑞新”的答案

            char[] s = string.Format("{0:X}", 999132).ToArray();
            int length = 1;
            if (s.Length>2)
            {
                length = s.Length/2;
                if (s.Length % 2 !=0)
                {
                    length ++;
                }
            }
            string[] slist = new string[length];
            int j = length-1;
            for (int i = 0; i < length; i++)
            {
                if (j * 2 + 1 < s.Length)
                {
                    slist[i] = string.Format("{1}{0}", s[i * 2], s[i * 2 - 1]);
                }
                else
                {
                    slist[i] = string.Format("{0}", s[i * 2]);
                }
                j--;
            }
            string sFormat = string.Join(" ", slist);
你的代码测试“999132”时没问题,但是测试“65535”就会出现问题
0
小耶果
小耶果
string.Format("{0:X}",value)
0
瑞新
瑞新
            char[] s = string.Format("{0:X}", 999132).ToArray();
            int length = 1;
            if (s.Length>2)
            {
                length = s.Length/2;
                if (s.Length % 2 !=0)
                {
                    length ++;
                }
            }
            string[] slist = new string[length];
            int j = length-1;
            for (int i = 0; i < length; i++)
            {
                if (j * 2 + 1 < s.Length)
                {
                    slist[i] = string.Format("{1}{0}", s[i * 2], s[i * 2 - 1]);
                }
                else
                {
                    slist[i] = string.Format("{0}", s[i * 2]);
                }
                j--;
            }
            string sFormat = string.Join(" ", slist);
0
Chouna
Chouna

引用来自“小耶果”的答案

string.Format("{0:X}",value)
这样只是实现了转换为十六进制,但不能实现单字节间用空格分隔
返回顶部
顶部