XAML 十进制与十六进制相互转换的逻辑实现

ztigrdn8  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(242)

我有两个单选按钮十进制和十六进制和一个文本框,当我在两个单选按钮之间切换时,文本框中的输入应该从十进制转换为十六进制,反之亦然,十进制是八位字节格式,如111,255,111.111,225.255.111.255
我需要逻辑转换为十六进制,反之亦然,例如,如果十进制是111.111.111,它应该转换为十六进制6F6F6F(不包括期间)时,十六进制转换为十进制它会显示
UI中的111.111.111(包括句点)
一些例子

111.111.111(DECIMAL) - 6F6F6F(HEXADECIMAL)
125.255.123(DECIMAL) - 7DFF7B(HEXADECIMAL)
7D(HEXADECIMAL) - 125(DECIMAL)
FF(HEXADECIMAL) - 255(HEXADECIMAL)

需要逻辑实现方面的帮助

krugob8w

krugob8w1#

我已经按照你在评论中的要求做出了解决方案。

将八进制转换为十六进制

此方法接受小于256的整数的输入,这些整数之间用句点分隔,如“111.111.111”,并将返回十六进制字符串,如“6f6f6f”。

public static string ConvertToHex(string Octets) 
{
    // Extract each part of the octet into individual number strings
    string[] numberStrings = Octets.Split('.');

    // Convert those strings to integers
    int[] numberList = Array.ConvertAll(numberStrings, s => int.Parse(s));

    // Create a string to store the final output in
    string HexString = string.Empty;

    // Loop through all the numbers in the int list
    foreach (int number in numberList)
    {
        // Convert the integer to a hex string and pad left with 0
        // This will ensure the hex number is always two digits long
        string HexSection = Convert.ToString(number, 16).PadLeft(2, '0');

        HexString += HexSection;
    }

    return HexString;                    
}

将十六进制字符串转换为八进制

此方法以十六进制字符串作为输入,每个十六进制值占两位数,并表示小于256的基数为10的值,例如“6f6f6f”,并将输出由小于256的数字组成的八位字节字符串,这些数字由句点分隔,例如“111.111.111”。

public static string ConvertToOctet(string Hex) 
{
    // Determine the length of the Hex string
    int Length = Hex.Length;

    // List to store all the hex we have converted to ints
    List<int> NumberList = new List<int>();

    // Calculate the length divided by two so the loop can iterate over each hex number which is two digits long
    int Iterations = Length / 2;

    // Loop through all the sections in the hex string
    for (int i = 0; i < Iterations; i++) 
    {
        // Extract the hex number which we know is two digits long
        string HexSegment = Hex.Substring(i * 2, 2);

        // Convert it to its integer value
        int Value = Convert.ToInt32(HexSegment, 16);

        // Add the int to the list of ints
        NumberList.Add(Value);
    }
    // Create a final list of octets split with a period
    string OctetString = string.Join(".", NumberList);

    return OctetString;
}

可以使用以下代码测试这些方法:

// Should output "6f6f6f"
Console.WriteLine(ConvertToHex("111.111.111"));

// Should output "c0a817fe78c86428"
Console.WriteLine(ConvertToHex("192.168.23.254.120.200.100.40"));

// Should output "111.111.111"
Console.WriteLine(ConvertToOctet("6f6f6f"));

// Should output "192.168.23.254.120.200.100.40"
Console.WriteLine(ConvertToOctet("c0a817fe78c86428"));

谢谢,如果有帮助的话,请把我的回答标记为接受和赞同👍

相关问题