我正在编写一个代码,该代码必须对 int8_t
数组执行一系列操作,其中每个元素都存储了一个数字,范围从 0 到 255。
int main(int argc, char *argv[]){
int8_t v = ... // Imagine it's an array equal to {1, 10, 100, 255}.
int y[4];
for(int i=0;i<3;i++)
y[i] = v[i]*3;
return 0;
}
我正在寻找的是一种使用 int8_t
数组进行操作的方法,或者最好是一种将 int8_t
转换为 int
的方法>s(我有一个与 int
输入一起工作的大代码,将 int8_t
转换为 int
然后将其提供给我的代码将需要更少的更改而不是将每个 int
更改为 int8_t
)。
可能还值得注意的是,int8_t
数组来自摄像机的视频捕获,它以 int8_t
形式返回从 0 到 255 的每个像素的值,这意味着我无法更改输入数组。
我们将不胜感激任何帮助。
编辑:
伪代码,希望能帮助说明我的问题。
int main(int argc, char *argv[]){
int8_t v[4] = {'0','1','2','3'};
int y;
y = (int) v[1]*3;
std::cout << v[1] << " " << y << std::endl;
return 0;
}
我运行时得到的输出是 1 49
。
最佳答案
您最近的编辑错误地初始化了数组。
int main(int argc, char *argv[]){
int8_t v[4] = {'0','1','2','3'}; // <- This is wrong!
int y;
y = (int) v[1]*3;
std::cout << v[1] << " " << y << std::endl;
return 0;
}
单引号中的数字是ASCII characters其数值与引号中的实际数字不匹配。
请像这样修改您的代码,看看是否有帮助:
int main(int argc, char *argv[]){
int8_t v[4] = {0, 1, 2, 3}; // <- Remove the single quotes
int y;
y = (int) v[1]*3;
std::cout << v[1] << " " << y << std::endl;
return 0;
}
这里是 ideone 的链接
跟进问题(来自评论):
I never declare the actual array, I import it directly from a .txt file. When I do this I get the same result as if I had declared it with the quotes. Is there a way to work around this, converting it from ascii code to the desired numeric value?
是的。您可以使用 atoi或 stoi函数将表示为文本的数字转换为整数。您还应该看看 this link讨论如何使用流运算符来实现相同的目的。
但是,从字符串转换数字非常简单,所以我给你举个例子:
#include <iostream>
#include <string.h>
int getNumberFromString(const char* numberString)
{
int number = 0;
int i;
int stringLength = strlen(numberString);
for (i = 0; i < stringLength; ++i)
{
number *= 10;
number += numberString[i] - '0';
}
return number;
}
int main()
{
const char* numberSeventyNineString = "79"; // Equivalent to { '7', '9', '\0' }
int numberSeventyNine;
numberSeventyNine = getNumberFromString(numberSeventyNineString);
std::cout << "Number (" << numberSeventyNineString << ") as int is: " << numberSeventyNine << std::endl;
return 0;
}
这是 ideone link
注意:行 const char* numberSeventyNineString = "79";//Equivalent to { '7', '9', '\0' }
有评论说这相当于一个数组,更多细节请看this answer
关于c++ - 将 int8_t 转换为 int,以便我可以对其执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951547/