Reputation: 873
how can I convert int to Byte Array, and Append other to byte array.
For Example
I want to convert it 151219 to `
new byte[6] { 0x31, 0x35, 0x31, 0x32, 0x31, 0x39 }`
And append to :
new byte[17] { 0x01, 0x52, 0x35, 0x02, 0x50, 0x31, 0x28, --- append here ---, 0x3B, 0x29, 0x03, 0x06 }
Upvotes: 0
Views: 2310
Reputation: 112762
You don't have an integer data type, you have a string containing an integer. That's quite different.
You can use ASCIIEncoding.GetBytes
byte[] bytes = (new System.Text.ASCIIEncoding()).GetBytes("151219");
You can concatenate two byte arrays like this (given two byte arrays a
and b
):
byte[] result = new byte[ a.Length + b.Length ];
Array.Copy( a, 0, result, 0, a.Length );
Array.Copy( b, 0, result, a.Length, b.Length );
By using
System.Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)
Upvotes: 1
Reputation: 6239
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" }
Upvotes: 1
Reputation: 83004
The following code will turn an int
into a byte
array representing each character of the value:
int value = 151219;
string stringValue = value.ToString(CultureInfo.InvariantCulture);
byte[] bytes = stringValue.Select(c => (byte) c).ToArray();
To insert it into your original array, something like this should do the trick:
private byte[] InsertInto(byte[] original, byte[] toInsert, int positionToInsert)
{
byte[] newArray = new byte[original.Length + toInsert.Length];
Array.Copy(original, newArray, positionToInsert);
Array.Copy(toInsert, 0, newArray, positionToInsert, toInsert.Length);
Array.Copy(original, positionToStart, newArray, positionToInsert + toInsert.Length, original.Length - positionToInsert);
return newArray;
}
Upvotes: 3