如何将十六进制字符串转换为十进制字符串 [英] How do I convert a hexadecimal string to a decimal string

查看:115
本文介绍了如何将十六进制字符串转换为十进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开展一个学校项目,该项目应该将IP地址转换为另一个数字系统,同时保留IP地址的一般语法并执行相同的操作,反之亦然,我目前遇到了问题尝试将十六进制值转换回十进制值时。



例如,我用来从十进制转换为十六进制的过程看起来像这样



I'm currently working on a school project that is supposed to convert IP Adresses into another number system, while keeping the general 'syntax' of an IP adress and do the same thing vice versa and I am currently running into a problem while trying to convert a hexadecimal value back to a decimal value.

The procedure I use to convert from decimal to hex, for example, would look like this

string DecimalToHex(string input)
{
    return String.Join(".", (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 16))).ToArray());
}





使用(字符串输入)作为文本框的文本。如果输入为c0,我希望输出为 - 当然 - 为192.



我尝试了什么:



我尝试了一些我在网上找到的东西,比如使用System.Globalization.NumberStyles.HexNumber,但到目前为止无济于事。



With (string input) being the text of a textbox. And if that input is "c0", I'd like the output to - of course - be 192.

What I have tried:

I've tried a few things I found around the net, like working with System.Globalization.NumberStyles.HexNumber, but to no avail so far.

推荐答案

首先避免使用复合语句,这样你就无法在每一步看到结果。使用 String.Split 获取包含四个字段的数组,然后将每个字段转换为其整数值。从那里你可以使用 String.Format方法(系统) )| Microsoft Docs [ ^ ]将它们显示为十进制值。并且一个小的改动将允许您将十进制字符串转换为十六进制。
Start by avoiding compound statements like that, where you cannot see the results at each step. Use String.Split to get an array containing the four fields, then convert each one to its integer value. From that you can use the String.Format Method (System) | Microsoft Docs[^] to display them as decimal values. And a minor change would allow you to convert decimal strings to hex.


这篇关于如何将十六进制字符串转换为十进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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