Sunday, July 14, 2024

how to convert array to vector in c++ fast way

array to vector

#include <vector>

constexpr int vec_size = 5;

float a[vec_size] = {0, 1, 2, 3, 4};

std::vector<float> vec_a(a, a + vec_size); // good


  1. https://sites.google.com/site/hashemian/home/tips-and-tricks/copy-array-cpp
  2. https://stackoverflow.com/questions/8777603/what-is-the-simplest-way-to-convert-array-to-vector
  3. https://www.freecodecamp.org/news/cpp-vector-how-to-initialize-a-vector-in-a-constructor/ <- how to initialize a vector from an array in C++

And vector to array

#include <vector>

constexpr int vec_size = 5;

float a[vec_size] = {0, 1, 2, 3, 4};

std::vector<float> vec_a(a, a + vec_size); // good


#include <algorithm>

float b[vec_size] = {}

std::copy(vec_a.begin(), vec_a.end(), b); // good

  1. https://stackoverflow.com/questions/2923272/how-to-convert-vector-to-array
  2. https://iq.opengenus.org/convert-vector-to-array-in-cpp/

Thursday, July 4, 2024

Python float to hexadecimal & hexadecimal to float, and default flaot vs. fp32

 import struct

def float_to_hex(f):

    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


def hex_to_float(h):

    return struct.unpack('!f', bytes.fromhex(h))[0]


hex_val = "0xbf557ca4"

float_val = hex_to_float(hex_val.replace("0x", ""))

print(f"-0.8339 -> 0xbf557ca4 -> {float_val} <- -0.8339331150054932")

----

-0.8339 -> 0xbf557ca4 -> -0.8339331150054932 <- -0.8339331150054932


import numpy as np

fp32_value = np.float32(-0.8339)

print(f"-0.8339 -> fp32: {fp32_value}")

----

output: -0.8339 -> fp32: -0.833899974822998


fp64_value = -0.8339

print(f"-0.8339 -> fp64: {fp64_value}")

----

output: -0.8339 -> fp64: -0.8339