-2

I'm trying to convert a string into int32 in C++. In Python, I used to do:

import numpy as np
str = "HELLO"
np.array([str]).view(np.int32)

This results in:

array([72, 69, 76, 76, 79], dtype=int32)

i.e., the ord of each char.

How can I achieve the same in C++?

P. S. I'm not looking for Numpy-style way to accomplish this. But, looking for possible ways to obtain the same results.

2 Answers2

0

In Python, this is what it does:

>>> import numpy as np
>>> str = "HELLO"
>>> np.array([str]).view(np.int32)
array([72, 69, 76, 76, 79])

In C/C++, "HELLO" already is the same thing as [72, 69, 76, 76, 79]!

static const char *s = "HELLO";
printf("%d\n", s[0]);   // prints 72
printf("%d\n", s[1]);   // prints 69
int x = s[2];   // x is now 76
printf("%d\n", x);   // prints 76
zvone
  • 18,045
  • 3
  • 49
  • 77
  • The code you posted is erroneous. Also, this is the default `int`, I want `int32_t`. – Yassen Mehrez Mar 31 '19 at 21:06
  • @YassenHatem Eh, nit-picking does not really make a difference. Anyways, now the code is no longer erroneous. If you want `int32_t` instead of `int` just replace `int` with `int32_t` in the code. – zvone Mar 31 '19 at 22:26
0

You could do something like:

auto arr = new int32_t[str.length()];

Then use std::transform as:

std::transform(str.begin(), str.end(), arr, [](char chr) -> int32_t { return int32_t(chr); });
ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51