Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting an array of integers into an array of bytes

Status
Not open for further replies.

Proqrammer

Programmer
Sep 17, 2006
64
Hi there, I have an array of integers such as:

Dim IntKey() As Integer = {123, 2, 120, 8, 246, 249, 140, 137, 136, 57, 64, 58, 1258, 5, 220}

Now I want to convert that array of integers into an array of bytes so that I could use it in cryptography.

How can I make that happen?
Any help is appreciated.
 
If you're going to pass this to another machine, be aware that since some of your values are > 255, that byte order will be a concern. So decide if the most-significant byte should be first or last in your array, and make sure the other side of your encryption knows this too.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thanks for your responses, I couldn't find a method in BitConverter class to do what I want to do, could you please give me an example?
 
Here's some hand-written C# code, maybe that will give you some ideas for a VB.NET equivalent.
Code:
using System;
using System.Collections.Generic;

private byte[] ToByteArray(int[] IntKey)
{
  List<byte> byteList = new List<byte>();

  foreach(int i in IntKey)
  {
     byteList.AddRange(BitConverter.GetBytes(i)); 
  }
  
  return byteList.ToArray();
}

Hope this helps.
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thanks for the help, it works perfectly, here is the code in V.net:


Imports System
Imports System.Collections.Generic

Private Function IntegerArray2ByteArray(ByVal IntegerArray() As Integer) As Byte()

Dim byteList As List(Of Byte) = New List(Of Byte)()

For Each i As Integer In IntegerArray
byteList.AddRange(BitConverter.GetBytes(i))
Next i

Return byteList.ToArray()
End Function

''' <summary>
''' Converting an array of integers into an array of bytes
''' </summary>
''' <param name="IntegerArray">An array of integers which is supposed to be converted</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function IntegerArray2ByteArray(ByVal IntegerArray() As Integer) As Byte()

Dim byteList As List(Of Byte) = New List(Of Byte)()

For Each i As Integer In IntegerArray
byteList.AddRange(BitConverter.GetBytes(i))
Next i

Return byteList.ToArray()
End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top