Get float values back from byte buffer?

I am learning C++ at the moment and currently I am experimenting with pointers and structures. In the following code, I am copying vector A into a buffer of size 100 bytes. Afterwards I copy vector B into the same buffer with an offset, so that the vectors are right next to each other in the buffer. Afterward, I want to find the vectors in the buffer again and calculate the dot product between the vectors.

#include <iostream>

const short SIZE = 5;

typedef struct vector {
    float vals[SIZE];
} vector;

void vector_copy (vector* v, vector* target) {
    for (int i=0; i<SIZE; i++) {
        target->vals[i] = v->vals[i];
    }
}

float buffered_vector_product (char buffer[]) {
    float scalar_product = 0;
    int offset = SIZE * 4;
    for (int i=0; i<SIZE; i=i+4) {
        scalar_product += buffer[i] * buffer[i+offset];
    }
    return scalar_product;
}

int main() {

    char buffer[100] = {};
    vector A = {{1, 1.5, 2, 2.5, 3}};
    vector B = {{0.5, -1, 1.5, -2, 2.5}};

    vector_copy(&A, (vector*) buffer);
    vector_copy(&B, (vector*) (buffer + sizeof(vector)));

    float prod = buffered_vector_product(buffer);
    std::cout << prod <<std::endl;
    return 0;
}

Unfortunately this doesn’t work yet. The problem lies within the function buffered_vector_product. I am unable to get the float values back from the buffer. Each float value should need 4 bytes. I don’t know, how to access these 4 bytes and convert them into a float value. Can anyone help me out? Thanks a lot!

Answer

In the function buffered_vector_product, change the lines

int offset = SIZE * 4;
for (int i=0; i<SIZE; i=i+4) {
    scalar_product += buffer[i] * buffer[i+offset];
}

to

for ( int i=0; i<SIZE; i++ ) {
    scalar_product += ((float*)buffer)[i] * ((float*)buffer)[i+SIZE];
}

If you want to calculate the offsets manually, you can instead replace it with the following:

int offset = SIZE * sizeof(float);
for ( int i=0; i<SIZE; i++ ) {
    scalar_product += *(float*)(buffer+i*sizeof(float)) * *(float*)(buffer+i*sizeof(float)+offset);
}

Leave a Reply

Your email address will not be published. Required fields are marked *