简体   繁体   English

C#:使用int和hex值创建一个字节数组

[英]C#: Create an byte array with int and hex values

I need to create a an byte array with hex and int values. 我需要用十六进制和整数值创建一个字节数组。

For example: 例如:

int value1 = 13;
int value2 = 31;
byte[] mixedbytes = new byte[] {0x09, (byte)value1, (byte)value2};

Problem: The 31 is converted to 0x1F. 问题:31转换为0x1F。 It should be 0x31. 它应该是0x31。 I've tried to convert the int values to string and back to bytes but that didn't solve the problem. 我试图将int值转换为字符串,然后再转换回字节,但这并不能解决问题。 The integers have never more than two digits. 整数不得超过两位数。

Try this: 尝试这个:

int value1 = 0x13;
int value2 = 0x31;
byte[] mixedbytes = new byte[] { 0x09, (byte)value1, (byte)value2 };

Also, you don't seem to understand conversion between decimal and hex. 另外,您似乎不了解十进制和十六进制之间的转换。 31 in decimal is 1F in hex, expecting it to be 31 in hex is a bad expectation for a better understanding of the conversion between decimal and hex, please have a look here: http://www.wikihow.com/Convert-from-Decimal-to-Hexadecimal 十进制的31是十六进制的1F,期望更好地理解十进制和十六进制之间的转换是不好的期望,请在此处查看: http : //www.wikihow.com/Convert-from -十进制到十六进制

I think you can try this method 我想你可以试试这个方法

    string i = "10";
    var b =  Convert.ToByte(i, 16)

In this method 10 will be stored as 0x10 在这种方法中10将被存储为0x10

This format is commonly known as Binary Coded Decimal (BCD). 这种格式通常称为二进制编码的十进制(BCD)。 The idea is that the nibbles in the byte each contain a single decimal digit. 这个想法是字节中的每个半字节都包含一个十进制数字。

In C#, you can do this conversion very easily: 在C#中,您可以非常轻松地进行此转换:

var number = 31;
var bcd = (number / 10) * 16 + (number % 10);

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

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