将int中的十六进制代码打印到字符串

时间:2016-12-12 08:44:42

标签: c# string hex

我需要使用string的{​​{1}}保存hexadecimal code

例如,int的{​​{1}}值为hexadecimal

我的问题是我必须将此代码保存在int 15中,如下所示:

xoooF

所以在这个问题中我有两个问题:

  • 第一个是如何自动将string转换为int myint = myStringLength; //this value might change string myIntExhCode = myint.convertThisIntoMyCode(); //and the string has to be exactly "/xoooF" 代码,如int

  • 第二个是如何创建一个包含hexadecimal的字符串,因为任何连接这样的字符串的尝试都会导致15 = xoooF,这是不正确的,因为在输出中我需要{{1要转换为\xoooF

我如何实现这两项任务?

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

你的问题很模糊。如果您想要十六进制格式,但将0(数字零)更改为o(小拉丁字母o),您可以实现 >扩展方法(为了保持您的建议代码不变):

 public static partial class IntExtensions {
   public static string convertThisIntoMyCode(this int value) {
     return "\\x" + value.ToString("X4").Replace('0', 'o'); // or "/x" + ... 
   }
 }

...

 int myint = myStringLength; //this value might change
 string myIntExhCode = myint.convertThisIntoMyCode();

 // Test output
 Console.Write(myIntExhCode);

答案 1 :(得分:1)

怎么样

int i = 15;
string result = "\\x" + i.ToString("X").PadLeft(4, 'o');
相关问题