简体   繁体   English

如何在c#中将Int64从十六进制转换为十六进制到十六进制

[英]How to convert from Int64 to hex and from hex to byte in c#

I am trying to send a byte array to micro controller over serial port. 我试图通过串口发送一个字节数组到微控制器。 This is an example array which can successfully communicate with micro controller: 这是一个可以与微控制器成功通信的示例数组:

byte[] getCommandArray = new byte[7] { 0x02, 0x0D, 0x01, 0x03, 0x30, 0x44, 0x03 };

What I need to do is read different values from database, store them in a byte array send this array to the serial port. 我需要做的是从数据库中读取不同的值,将它们存储在一个字节数组中,将此数组发送到串行端口。 I read values from database as Int64 . 我从Int64读取数据库中的值。 Also for a successful communication I need to convert these values to hex. 另外,为了成功通信,我需要将这些值转换为十六进制。 For example if I read 13 from the database I need to write this to my array as 0x0D. 例如,如果我从数据库中读取13,我需要将其作为0x0D写入我的数组。 I can convert 13 to 0x0D as hex string but I can't convert this to byte . 我可以将13转换为0x0D作为十六进制字符串,但我无法将其转换为byte If you have any other suggestions than this logic I would be appreciated. 如果您有任何其他建议而非此逻辑,我将不胜感激。

If you simply want to get all of the bytes from your Int64 value, you can do that like this: 如果您只想从Int64值中获取所有字节,可以这样做:

Int64 myValueFromDB = 13;
var asBytes = BitConverter.GetBytes(myValueFromDB);

To check if this produces what you expect, you can print this result like this: 要检查这是否产生了您的期望,您可以打印此结果,如下所示:

Console.WriteLine("{{{0}}}", string.Join(",", asBytes.Select(x => "0x" + x.ToString("X2"))));    

For your example, using the value of 13 for myValueFromDB , the output is: 对于您的示例,对myValueFromDB使用值13,输出为:

{0x0D,0x00,0x00,0x00,0x00,0x00,0x00,0x00}

As you can see, the value of asBytes[0] is 0x0D, the other 7 bytes are 0. 如您所见, asBytes[0]值为0x0D,其他7个字节为0。

You can check this for yourself in this Fiddle ; 你可以在这个小提琴中自己检查一下;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM