3

I have data in the form of

float [1000,2] data.

I want to convert that data in the form of byte []b.

and again I want to convert byte []b to 2 dimensional array of float [1000,2] data

I want to do this because i can save data to server in the form of byte easily.

3
  • duplicate of stackoverflow.com/questions/4742910/… Commented Mar 20, 2013 at 11:46
  • Do you expect four bytes per float? Commented Mar 20, 2013 at 11:46
  • i want to convert 2 dimensional float array(float [1000,2] data) to one dimensional byte array(mean byte []b) Commented Mar 20, 2013 at 11:51

1 Answer 1

4

You could use these methods. They use simple programing structures and I think it won't be hard to understand them. The first method converts the float 2Dimansional array into one array of bytes. It first declares byte array and then each float value converts to 4 bytes and stores them into the big byte array.

    public byte[] ToByteArray(float[,] nmbs)
    {
        byte[] nmbsBytes = new byte[nmbs.GetLength(0) * nmbs.GetLength(1)*4];
        int k = 0;
        for (int i = 0; i < nmbs.GetLength(0); i++)
        {
            for (int j = 0; j < nmbs.GetLength(1); j++)
            {
                byte[] array = BitConverter.GetBytes(nmbs[i, j]);
                for (int m = 0; m < array.Length; m++)
                {
                    nmbsBytes[k++] = array[m];
                }
            }
        }
        return nmbsBytes;
    }

The second method converts from byte array to 2Dimensional float array. It first declares the array and then each four bytes converts to the float number which is afterwards stored to the specified position in 2D float array.

    public float[,] ToFloatArray(byte [] nmbsBytes)
    {
        float[,] nmbs = new float[nmbsBytes.Length /4 / 2, 2];
        int k = 0;
        for (int i = 0; i < nmbs.GetLength(0); i++)
        {
            for (int j = 0; j < nmbs.GetLength(1); j++)
            {
                nmbs[i, j] = BitConverter.ToSingle(nmbsBytes,k);
                k += 4;
            }
        }
        return nmbs;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.