C# Int to Byte[]

C# int to byte[]

The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.

Now, you are most probably working on a little-endian machine and BitConverter.GetBytes() will give you the byte[] reversed. So you could try:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;

For the code to be most portable, however, you can do it like this:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;

Converting an int[] to byte[] in C#

If you want a bitwise copy, i.e. get 4 bytes out of one int, then use Buffer.BlockCopy:

byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);

Don't use Array.Copy, because it will try to convert and not just copy. See the remarks on the MSDN page for more info.

Int to byte array

Update for 2020 - BinaryPrimitives should now be preferred over BitConverter. It provides endian-specific APIs, and is less allocatey.


byte[] bytes = BitConverter.GetBytes(i);

although note also that you might want to check BitConverter.IsLittleEndian to see which way around that is going to appear!

Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>> / <<), or by using unsafe code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.

C# int byte conversion

Surprisingly, when you perform operations on bytes the computations will be done using int values, with the bytes implicitly cast to (int) first. This is true for shorts as well, and similarly floats are up-converted to double when doing floating-point arithmetic.

The second snippet is equivalent to:

byte someVar;
someVar = (int) someVar - 3;

Because of this you must cast the result back to (byte) to get the compiler to accept the assignment.

someVar = (byte) (someVar - 3);

Convert listint[] to byte[]

How about this:

byte[] bytes =
lista
.SelectMany(x => x)
.SelectMany(BitConverter.GetBytes)
.ToArray();

UPDATE:

To convert the result to List<int>, you can do the following:

List<int> list =
bytes
.Select((item, index) => new {item, index})
.GroupBy(x => x.index/4)
.Select(g => g.Select(x => x.item).ToArray())
.Select(x => BitConverter.ToInt32(x, 0))
.ToList();

Write int into byte with the length of 4

I would seriously implore you to quit the idea of sending and receiving messages in binary and to use some textual format like xml, json, anything but binary, really.

If you insist on using a binary format, then the BinaryWriter and MemoryStream approach is perfectly fine.

If, for whatever reason, you don't like that, then you can try this:

byte[] bytes = new byte[5];
bytes[0] = messageType;
bytes[1] = (byte)(messageLength & 0xff);
bytes[2] = (byte)((messageLength >> 8) & 0xff);
bytes[3] = (byte)((messageLength >> 16) & 0xff);
bytes[4] = (byte)((messageLength >> 24) & 0xff);

Can't convert int to byte

You're using Convert.ToInt32() when you're assigning a byte. Use Convert.ToByte() instead.

Even better would be to use TryParse instead to avoid exceptions when the string isn't valid:

byte alength;
bool success = Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength);

If the parsing succeedded success will be true, otherwise false.
You can define the flow of your program depending on whether the conversion succeeds or not:

byte alength;
if(Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength))
{
//Great success! continue program
}
else
{
//Oops something went wrong!
}

Integer to Byte Array In C#

You can create a AppendInto method that will append arrays, and use Encoding.ASCII.GetBytes to convert string to byte array.

private byte[] AppendInto(byte[] original, byte[] toInsert, int appendIn)
{
var bytes = original.ToList();
bytes.InsertRange(appendIn, toInsert);
return bytes.ToArray();
}

Then just use the function

var toInsert = Encoding.ASCII.GetBytes("151219");

var original = new byte[11] { 0x01, 0x52, 0x35, 0x02, 0x50, 0x31, 0x28, 0x3B, 0x29, 0x03, 0x06 };
AppendInto(original, toInsert, 7);

Result

byte[17] { "0x01", "0x52", "0x35", "0x02", "0x50", "0x31", "0x28", "0x31", "0x35", "0x31", "0x32", "0x31", "0x39", "0x3B", "0x29", "0x03", "0x06" }

C# Converting an int into an array of 2 bytes

You need to shift the 1st byte:

 //profile_num[0] = (byte) ((profile_number & 0xFF00));
profile_num[0] = (byte) ((profile_number & 0xFF00) >> 8);
profile_num[1] = (byte) ((profile_number & 0x00FF));

int to byte[] consistency over network

Your current approach will not work for the case when your application running on system which use Big-Endian. In this situation you don't need reordering at all.

You don't need to reverse byte arrays by your self

And you don't need check for endianess of the system by your self

Static method IPAddress.HostToNetworkOrder will convert integer to the integer with big-endian order.

Static method IPAddress.NetworkToHostOrder will convert integer to the integer with order your system using

Those methods will check for Endianness of the system and will do/or not reordering of integers.

For getting bytes from integer and back use BitConverter

public struct ThreeIntegers
{
public int One;
public int Two;
public int Three;
}

public static byte[] ToBytes(this ThreeIntegers value )
{
byte[] bytes = new byte[12];
byte[] bytesOne = IntegerToBytes(value.One);
Buffer.BlockCopy(bytesOne, 0, bytes, 0, 4);

byte[] bytesTwo = IntegerToBytes(value.Two);
Buffer.BlockCopy(bytesTwo , 0, bytes, 4, 4);

byte[] bytesThree = IntegerToBytes(value.Three);
Buffer.BlockCopy(bytesThree , 0, bytes, 8, 4);

return bytes;
}

public static byte[] IntegerToBytes(int value)
{
int reordered = IPAddress.HostToNetworkOrder(value);
return BitConverter.GetBytes(reordered);
}

And converting from bytes to struct

public static ThreeIntegers GetThreeIntegers(byte[] bytes)
{
int rawValueOne = BitConverter.ToInt32(bytes, 0);
int valueOne = IPAddress.NetworkToHostOrder(rawValueOne);

int rawValueTwo = BitConverter.ToInt32(bytes, 4);
int valueTwo = IPAddress.NetworkToHostOrder(rawValueTwo);

int rawValueThree = BitConverter.ToInt32(bytes, 8);
int valueThree = IPAddress.NetworkToHostOrder(rawValueThree);

return new ThreeIntegers(valueOne, valueTwo, valueThree);
}

If you will use BinaryReader and BinaryWriter for saving and sending to another platforms then BitConverter and byte array manipulating can be dropped off.

// BinaryWriter.Write have overload for Int32
public static void SaveThreeIntegers(ThreeIntegers value)
{
using(var stream = CreateYourStream())
using (var writer = new BinaryWriter(stream))
{
int reordredOne = IPAddress.HostToNetworkOrder(value.One);
writer.Write(reorderedOne);

int reordredTwo = IPAddress.HostToNetworkOrder(value.Two);
writer.Write(reordredTwo);

int reordredThree = IPAddress.HostToNetworkOrder(value.Three);
writer.Write(reordredThree);
}
}

For reading value

public static ThreeIntegers LoadThreeIntegers()
{
using(var stream = CreateYourStream())
using (var writer = new BinaryReader(stream))
{
int rawValueOne = reader.ReadInt32();
int valueOne = IPAddress.NetworkToHostOrder(rawValueOne);

int rawValueTwo = reader.ReadInt32();
int valueTwo = IPAddress.NetworkToHostOrder(rawValueTwo);

int rawValueThree = reader.ReadInt32();
int valueThree = IPAddress.NetworkToHostOrder(rawValueThree);
}
}

Of course you can refactor methods above and get more cleaner solution.

Or add as extension methods for BinaryWriter and BinaryReader.



Related Topics



Leave a reply



Submit