C# 将字符转换为字节(十六进制表示)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12527694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:34:54  来源:igfitidea点击:

C# Convert Char to Byte (Hex representation)

c#bytetype-conversionhex

提问by DropTheCode

This seems to be an easy problem but i can't figure out.

这似乎是一个简单的问题,但我无法弄清楚。

I need to convert this character <in byte(hex representation), but if i use

我需要将此字符<转换为字节(十六进制表示),但如果我使用

byte b = Convert.ToByte('<');

i get 60(decimal representation) instead of 3c.

我得到60(十进制表示)而不是3c

采纳答案by Henk Holterman

60 == 0x3C.

60 == 0x3C.

You already have your correct answer but you're looking at it in the wrong way.

您已经有了正确的答案,但您以错误的方式看待它。

0xis the hexadecimal prefix
3Cis 3 x 16 + 12

0x是十六进制前缀
3C是 3 x 16 + 12

回答by Darin Dimitrov

You could use the BitConverter.ToStringmethod to convert a byte array to hexadecimal string:

您可以使用该BitConverter.ToString方法将字节数组转换为十六进制字符串:

string hex = BitConverter.ToString(new byte[] { Convert.ToByte('<') });

or simply:

或者干脆:

string hex = Convert.ToByte('<').ToString("x2");

回答by Matthew Watson

You want to convert the numeric value to hex using ToString("x"):

您想使用以下方法将数值转换为十六进制ToString("x")

string asHex = b.ToString("x");

However, be aware that you code to convert the "<" character to a byte will work for that particular character, but it won't work for non-ANSI characters (that won't fit in a byte).

但是,请注意,将“<”字符转换为字节的代码适用于该特定字符,但不适用于非 ANSI 字符(无法放入字节)。

回答by cc4re

char ch2 = 'Z';
Console.Write("{0:X} ", Convert.ToUInt32(ch2));

回答by Heinzi

get 60 (decimal representation) instead of 3c.

得到 60(十进制表示)而不是 3c。

No, you don't get any representation. You get a bytecontaining the value 60/3c in some internalrepresentation. When you look at it, i.e., when you convert it to a string (explicitly with ToString()or implicitly), you get the decimal representation 60.

不,你没有任何代表。您会byte在某些内部表示中得到一个包含值 60/3c 的值。当您查看它时,即当您将其转换为字符串(显式使用ToString()或隐式)时,您会得到十进制表示 60

Thus, you have to make sure that you explicitlyconvert the byte to string, specifying the base you want. ToString("x"), for example will convert a number into a hexadecimalrepresentation:

因此,您必须确保将字节显式转换为字符串,并指定所需的基数ToString("x"),例如将数字转换为十六进制表示:

byte b = Convert.ToByte('<');  
String hex = b.ToString("x");