[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 386
  • Last Modified:

How to convert Java's squashBytesToInts() and spreadIntsToBytes() functions in C Sharp?

I'm converting Java code to C-sharp and came across squashBytesToInts and spreadIntsToBytes which is not built-in in C-Sharp. How is it done in C Sharp?
0
ludy
Asked:
ludy
  • 2
  • 2
1 Solution
 
Jaime OlivaresCommented:
there are many ways to do it, you can use BitConverter:

static byte[] spreadIntsToBytes(int[] ints)
{
      byte[] result = new byte[ints.Length*4];
      for (int i = 0; i<ints.Length; i++)
            Array.Copy( BitConverter.GetBytes(ints[i]), 0, result, i*4, 4);
      return result;
}            
static int[] squashBytesToInts(byte[] bytes)
{
      int size = bytes.Length >> 2;  // divide by 4
      int[] result = new int[size];
      for (int i = 0; i<size; i++)
            int[i] = BitConverter.ToInt32(bytes, i*4);
      return result;
}
           
 
0
 
ludyAuthor Commented:
Thanks but, the functions used are presented with four parameters:

squashBytesToInts (byte[] inBytes, int inOff, int[] outInts, int outOff, int intLen)
spreadIntsToBytes (int[] inInts, int inOff, byte[] outBytes, int outOff, int intLen)

How would it translate given these four parameters?
0
 
ludyAuthor Commented:
I mean 5 parameters
0
 
Jaime OlivaresCommented:
hmmm, I will try to do it by hand:

void spreadIntsToBytes (int[] inInts, int inOff, byte[] outBytes, int outOff, int intLen)
{
      for (int i = 0; i<intLen; i++)
            Array.Copy(BitConverter.GetBytes(inInts[i+inOff]), 0, outBytes, (i+outOff)*4, 4);
}            

void squashBytesToInts (byte[] inBytes, int inOff, int[] outInts, int outOff, int intLen)
{
      for (int i = 0; i<intLen; i++)
            outInts[i+outOff] = BitConverter.ToInt32(inBytes, (i+inOff)*4);
}
0

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now