1

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. It should be 0x31. I've tried to convert the int values to string and back to bytes but that didn't solve the problem. The integers have never more than two digits.

7
  • Why should it be 0x31? Commented May 26, 2016 at 6:12
  • I've a serial device that only accept it in that format. Commented May 26, 2016 at 6:13
  • 0x1f if the hex representation of the integer 31. 0x31 would be 49. Commented May 26, 2016 at 6:15
  • Ok - sorry I wasn't clear enough: I need to write an byte array or string array to that device. That device has to store the number 31 as the number 31 - not 1F. Commented May 26, 2016 at 6:16
  • Well, it's surely it's storing it as 00011111? Commented May 26, 2016 at 6:19

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

If they want (as they claim) the integer values of 13 and 31; this is not a solution.
It is a solution if the OP, reads the article and understands the conversion and can then decide for themselves how to proceed. Also, the OP never indicated that they wanted a decimal value of 13 and 31, only that they wanted a hex value of 0x31, you're assuming they want 13 and 31. This is precisely why I included the article because it's unclear what they want and they need to understand the conversion to continue.
0

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

Comments

0

This format is commonly known as Binary Coded Decimal (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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.