Welcome Guest ( Log In | Register )

Outline · [ Standard ] · Linear+

 converting datatype from array to another

views
     
TSnarf03
post Mar 24 2024, 02:18 AM, updated 2y ago

Look at all my stars!!
*******
Senior Member
4,547 posts

Joined: Dec 2004
From: Metro Prima, Kuala Lumpur, Malaysia, Earth, Sol


Lets say i have 2 arrays source and destination.

source array consists of 1000 items of 32bit float, that their value ranged from 1.0f to -1.0f

destination array consists of 2000 bytes

i want to convert each float to 2 byte(16 bit), value ranged 32767 to -32768(00 00 to FF FF), little-endian

i manage to do byte by byte calculation, but its a bit slow, any efficient way to do it ?

This post has been edited by narf03: Mar 24 2024, 02:25 AM
TSnarf03
post Mar 24 2024, 07:44 PM

Look at all my stars!!
*******
Senior Member
4,547 posts

Joined: Dec 2004
From: Metro Prima, Kuala Lumpur, Malaysia, Earth, Sol


QUOTE(cheesey @ Mar 24 2024, 06:21 AM)
CODE

#include <cstdint>
#include <iostream>
#include <vector>

// Function to convert float in range [-1.0f, 1.0f] to int16_t
int16_t float_to_int16(float value) {
   // Clamp the value to the range [-1.0f, 1.0f]
   value = value > 1.0f ? 1.0f : value < -1.0f ? -1.0f : value;
   return static_cast<int16_t>(value * 32767.0f);
}

// Function to convert an array of floats to an array of int16_t
std::vector<int16_t> convert_float_array(const std::vector<float>& source) {
   std::vector<int16_t> destination;
   destination.reserve(source.size());

   for (float value : source) {
       destination.push_back(float_to_int16(value));
   }

   return destination;
}

int main() {
   // Example usage
   std::vector<float> source = {/* ... fill with your 1000 float values ... */};
   std::vector<int16_t> destination = convert_float_array(source);

   // Output the converted values
   for (int16_t value : destination) {
       std::cout << value << " ";
   }

   return 0;
}


Not tested
*
not dont know how to do it, i wonder if there is a more efficient way of doing it not byte by byte, my example is 1000 items, in reality, it will be far more.

 

Change to:
| Lo-Fi Version
0.0185sec    0.52    6 queries    GZIP Disabled
Time is now: 24th December 2025 - 01:33 AM