-1

I want to add two 32-bit values into byte[8] in big endian style.

int a = 1; // => [ 0, 0, 0, 1]
int b = 2; // => [ 0, 0, 0, 2]

resulting in

[0, 0, 0, 1, 0, 0, 0, 2]

So what is the one liner for this?

My approach so far was

int a = 1;
int b = 2;

byte[] array = new byte[] { };
array = array.Concat(BitConverter.GetBytes(a)).ToArray();
array = array.Concat(BitConverter.GetBytes(b)).ToArray();

so this is already complicated enough but little endian. So I would add a line for each int to get them reversed.

Two talk in python:

a = 1;
b = 2;
array = a.to_bytes(4, 'big') + b.to_bytes(4, 'big')

What is the C# method for this?

14
  • 3
    Well, some of your own choices here are a little odd. I.e. it's unclear why you don't just have var array = BitConverter.GetBytes(a).Concat(BitConverter.GetBytes(b)).ToArray() instead of e.g. creating an empty array first and storing an intermediate form where just a has been added to the array. You notably don't seem to do these same things in the Python version... Commented Mar 16, 2021 at 13:16
  • (a<< 16) + b. You are adding two int16 values. Commented Mar 16, 2021 at 13:18
  • 1
    There is a new BinaryPrimitives library if you have access to dotNET 3.1 in your project. Commented Mar 16, 2021 at 13:18
  • 1
    Does this answer your question? C# int to byte[] or this answer. Commented Mar 16, 2021 at 13:18
  • 1
    Be careful of negative numbers which is using 2'scompliment sign extension. Are your number sign or unsign? Commented Mar 16, 2021 at 13:41

1 Answer 1

1

BitConverter endianness is dependent on the platform on which it is executing, so you'll have to make a check to BitConverter.IsLittleEndian and do some conditional .Reverse()-ing of the results from BitConverter.GetBytes(a).

byte[] array = (BitConverter.IsLittleEndian ?
  BitConverter.GetBytes(a).Reverse().Concat(BitConverter.GetBytes(b).Reverse()) : 
  BitConverter.GetBytes(a).Concat(BitConverter.GetBytes(b))
).ToArray();

(I wouldn't necessarily do it as a one-liner as you asked, but you can create useful functions with more economical syntax from this example.)

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

1 Comment

Thx for you input. Well no, I wouldn't force this into a one liner just to achieve a one liner. With one liner I for sure simply mean a short tiny pretty solution (like in python). Your solution then would violate our "max. 150 symbols on one line" 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.