问题描述
我需要的ASCII转换为十六进制值。请参阅ASCII表,但我有下面几个例子所示:
I need to convert ascii to hex values. Refer to the Ascii table but I have a few examples listed below:
- ASCII 1 = 31
- 2 = 32
- 3 = 33
- 4 = 34
- 5 = 35
- A = 41
- A = 61等
- ascii 1 = 31
- 2 = 32
- 3 = 33
- 4 = 34
- 5 = 35
- A = 41
- a = 61 etc
但我我使用int,而不是字符串值。是否有可能做到这一点。
所以诠释测试= 12345;
需要得到转换I = 3132333435
But I am using int instead of string values. Is it possible to do that.Therefore int test = 12345;Need to get the converted i = 3132333435
推荐答案
测试此
string input = "12345";
string hex = string.Join(string.Empty,
input.Select(c => ((int)c).ToString("X")).ToArray());
Console.WriteLine(hex);
请注意:在C#4,调用.ToArray()是没有必要的,因为的string.join方法已重载接受的IEnumerable< T>
Note: in C# 4, the call to .ToArray() is not necessary because the string.Join method has been overloaded to accept IEnumerable<T>
.
以上将真正的ASCII工作,因为第一UTF16 128代码点(在C#中的使用的编码字符串
键入)具有相同的数值为ASCII,所以铸造C#字符
值 INT
的罚款。然而,经常被称作是ASCII实在是有些ANSI代码页(在美国,通常代码页1252,西欧(Windows的),其中有256码点,没有作为相同的值第二个128在UTF16使用。
The above will work for real ASCII, because the first 128 code points of UTF16 (the encoding used in C#'s string
type) have the same numeric values as for ASCII, and so casting the C# char
value to int
is fine. However, often what is described as "ASCII" is really some ANSI code page (in the US, usually code page 1252, "Western European (Windows"), which has 256 code points, the second 128 not having the same values as that used in UTF16.
如果您正在处理的,或与此有关的任何其他代码页,你有文本为C#字符串
,您可以应用相同的技术上面,除了使用编码
类转换的C#字符串
对象到字节[]
转换为十六进制前:
If you are dealing with that, or any other code page for that matter, and you have the text as a C# string
, you can apply the same technique as above, except using the Encoding
class to convert the C# string
object to a byte[]
before converting to hexadecimal:
string input = "12345";
// Replace 1252 with whatever code page you're using, if not that one
string hex = string.Join(string.Empty,
Encoding.GetEncoding(1252).GetBytes(input).Select(b => b.ToString("X")).ToArray());
Console.WriteLine(hex);
这篇关于需要ASCII值转换为十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!