C#将int转换为hex int

时间:2016-11-05 05:27:02

标签: c#

好的,所以每个人都说要使用:

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

但是这不起作用。这是每次有人问的答案,但是当我这样做时,我的整数仍然会被转换回十进制。

这不是一个重复的问题,因为其他所有问题都有错误的答案,因为这实际上并不起作用。将int转换为hex int的真正方法是什么?这样做只会将intAgain保持为十进制182。

1 个答案:

答案 0 :(得分:1)

声明int intValue = 182;时,在内存中分配32位(4字节)。 由于内存只能存储二进制值,因此将182存储在内存中,如下所示:

00000000 #Byte 1
00000000 #Byte 2
00000000 #Byte 3
10110110 #Byte 4 

执行string hexValue = intValue.ToString("X");时,会在内存中分配一组字符来表示字符串 数字182,十六进制是B6 每个字符都存储为二进制,并设置为数字B6的数字 在内存中保存为二进制的字符使用UTF-16标准进行编码(每个字符需要2个字节) 变量hexValue的内存表示示例

   01000010 #Byte 1 (char 'B') 
   00000000 #Byte 2
   00110110 #Byte 3 (char '6')
   00000000 #Byte 4 

使用int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);,您可以将字符串再次转换为数字:

00000000 #Byte 1
00000000 #Byte 2
00000000 #Byte 3
10110110 #Byte 4 

int类型不存储数字基数,只在内存中存储二进制值,十六进制或十进制只是表示值的一种方式,只有当你转换一个值时才能这样做。可读的字符串。

相关问题