简体   繁体   中英

Integer to Byte Array In C#

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 }

http://www.nthelp.com/ascii.htm

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;
}

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)

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" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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