Reinterpret float vector as an unsigned array of char and back

I searched and searched for stackoverflow for an answer, but didn't find what I needed.

I have a routine that takes an unsigned char array as a parameter to encode it as Base64. I would like to encode the STL vector (vector) vector in Base64 and, therefore, would have to re-interpret the bytes in the float vector as an array of unsigned characters in order to pass it to the encoding procedure. I tried several things from reinterpretation and static throws, copies of mem, etc., but none of them work (at least not in the way I implemented them).

Similarly, when decoding encoded data back to a floating-point array, I would need to do the exact opposite. The decoding routine will provide the decoded data as an unsigned array of char, and I will need to re-interpret this array of bytes, again converting it to a float vector.

Here is a cut out version of my C ++ code to do the encoding:

std::string
EncodeBase64FloatVector( const vector<float>& p_vector )
{
  unsigned char* sourceArray;

  // SOMEHOW FILL THE sourceArray WITH THE FLOAT VECTOR DATA BITS!!

  char* target;
  size_t targetSize = p_vector.size() * sizeof(float);
  target = new char[ targetSize ];

  int result = EncodeBase64( sourceArray, floatArraySizeInUChars, target, targetSize );

  string returnResult;
  if( result != -1 )
  {
    returnResult = target;
  }
  delete target;
  delete sourceArray;
  return returnResult;
}

Any help would be greatly appreciated. Thank.

Raymond

+3
source share
3 answers

std::vector guarantees that the data will be contiguous, and you can get a pointer to the first element in the vector by taking the address of the first element (assuming that it is not empty).

typedef unsigned char byte;
std::vector<float> original_data;
...
if (!original_data.empty()) {
  const float *p_floats = &(original_data[0]);  // parens for clarity

, unsigned char, reinterpret_cast:

  const byte *p_bytes = reinterpret_cast<const byte *>(p_floats);
  // pass p_bytes to your base-64 encoder
}

, .

: . , ( ), .

+7
sourceArray = reinterpret_cast<const unsigned char *>(&(p_vector[0]))
+5

Google protobuf, . , . , , - , .

, base64, protobuf , , 8- . .

0
source

Source: https://habr.com/ru/post/1726461/


All Articles