在 C# 中使用 int 作为字符串的数字表示
我尝试使用整数作为字符串的数字表示形式,例如,将“ABCD”存储为 0x41424344。然而,当涉及到输出时,我必须将整数转换回 4 个 ASCII 字符。现在,我正在使用位移位和掩码,如下所示:
int value = 0x41424344;
string s = new string (
new char [] {
(char)(value >> 24),
(char)(value >> 16 & 0xFF),
(char)(value >> 8 & 0xFF),
(char)(value & 0xFF) });
有没有更干净的方法来做到这一点?我尝试了各种类型转换,但编译器正如预期的那样抱怨了它。
I'm trying to use an integer as the numerical representation of a string, for example, storing "ABCD" as 0x41424344. However, when it comes to output, I've got to convert the integer back into 4 ASCII characters. Right now, I'm using bit shifts and masking, as follows:
int value = 0x41424344;
string s = new string (
new char [] {
(char)(value >> 24),
(char)(value >> 16 & 0xFF),
(char)(value >> 8 & 0xFF),
(char)(value & 0xFF) });
Is there a cleaner way to do this? I've tried various casts, but the compiler, as expected, complained about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字符是 16 位的,因此您必须将它们编码为 8 位值才能将它们打包为整数。您可以使用
Encoding
类在字符和字节之间进行转换,使用BitConverter
类在字节和整数之间进行转换以下是两种转换方式:
请注意字节的顺序整数取决于计算机的字节顺序。在小端系统上,“ABCD”的数值将为 0x44434241。要获得相反的顺序,您可以反转字节数组:
或者如果您使用的是框架 3.5:
Characters are 16 bit, so you have to encode them into eight bit values to pack them in an integer. You can use the
Encoding
class to convert between characters and bytes, and theBitConverter
class to convert between bytes and integerHere is conversion both ways:
Note that the order of the bytes in the integer depends on the endianess of the computer. On a little endian system the numeric value of "ABCD" will be 0x44434241. To get the reverse order, you can reverse the byte array:
Or if you are using framework 3.5:
(上面假设您在小端系统上运行。对于大端系统,您可以删除
.Reverse().ToArray()
部分,尽管如果您在小端系统上运行,那么如果可能的话,首先将“ABCD”存储为 0x44434241 可能更有意义。)(The above assumes that you're running on a little-endian system. For big-endian you could just drop the
.Reverse().ToArray()
part, although if you are on a little-endian system then it would probably make more sense for you to just store "ABCD" as 0x44434241 in the first place, if possible.)它将根据您的需要将字符串转换为十六进制。
It will convert string to hex as you required.
如果字符串不超过 8 个字符并且是一种十六进制字符串,您可以使用
基变量 16 查看 Convert 类中的 Conversion 函数。
问候
哎呀
if the string is never longer than 8 chars and a kind of Hexstring, you could use
the base variable 16 have a look at the Conversion functions from the Convert class.
regards
Oops