字符串到字节数组的转换 [英] String to Byte Array Conversion
本文介绍了字符串到字节数组的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将字符串(代表十进制值)转换为字节数组?
假设用户输入1000,程序将生成{E8,03,00,00}
1000000将给出{40,42,0F,00}
是否有执行此功能的功能?我记得我以前见过类似的东西,但我不记得在哪里.也许我在做白日梦.
无论如何,谢谢预先感谢您的评论和帮助...
How do you convert from a string (that represents a decimal value) to a byte array?
Let says the users enter 1000 the program would produce {E8, 03, 00, 00}
And 1000000 will give {40, 42, 0F, 00}
Is there a function that does this? I remember that I saw something like this before but I can not remember where. Maybe I was day dreaming.
Anyway, thanks In advance thanks for the comments and help...
推荐答案
这是两个不同的目标:1)序列化一般情况的字符串;可以使用System.Text.Encoding
完成,结果取决于所使用的编码;如果编码表示Unicode UTF之一,则所有结果将有所不同,但等效,并且未能使用UTF可能会导致数据丢失(请考虑"???"字符); 2)序列化由字符串表示的数字.
在第二种情况下,它与string
无关.您应该使用数据,而不是代表数据的字符串.这些字符串只能用于在UI,人类可读文件等中呈现数据.
无论如何,您可以使用它们的Parse
或TryParse
方法将字符串解析为任何数字类型.例如:
http://msdn.microsoft.com/en-us/library/system.uint32. parse.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.uint32. tryparse.aspx [ ^ ].
(请参阅您可能需要的其他数字类型.)
然后,您可以将数值序列化为字节数组,然后再返回.请参阅课程System.BitConverter
:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx [^ ].
-SA
Those are two different goals: 1) serialize a general-case string; which can be done usingSystem.Text.Encoding
, and the result depends on the encoding used; if the encoding represents one of Unicode UTFs, all results will be different but equivalent, and the failure to use UTF can lead to data loss (think ''????'' characters); 2) serialization of a number represented by a string.
In the second case, it has nothing to do withstring
. You should work with data, not with the strings representing data. The strings can be used only for presentation of data in UI, human-readable files and the like.
Anyway, you can parse a string to any numeric type using theirParse
orTryParse
methods. For example:
http://msdn.microsoft.com/en-us/library/system.uint32.parse.aspx[^],
http://msdn.microsoft.com/en-us/library/system.uint32.tryparse.aspx[^].
(Please see other numeric types you might need.)
And then, you can serialize numeric value to array of bytes — and back. Please see the classSystem.BitConverter
:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx[^].
—SA
您是否可以使用 ^ ]
Could you use Conversion.Hex Method [^]
您是否正在考虑旧的 ^ ]函数?
Are you thinking of the old Hex()[^] function?
这篇关于字符串到字节数组的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文