如何将 char 数组转换为单个整数?
我正在尝试读取 PNG 文件的内容.
i'm trying to read contents of PNG file.
您可能知道,所有数据都以 4 字节的方式写入 png 文件,包括文本和数字.因此,如果我们有编号 35234,则以这种方式保存:[1000][1001][1010][0010].
As you may know, all data is written in a 4-byte manner in png files, both text and numbers. so if we have number 35234 it is save in this way: [1000][1001][1010][0010].
但有时数字更短,所以第一个字节为零,当我读取数组并将其从 char* 转换为整数时,我得到了错误的数字.例如 [0000] [0000] [0001] [1011]有时数字被误解为负数,有时被误解为零!
but sometimes numbers are shorter, so the first bytes are zero, and when I read the array and cast it from char* to integer I get wrong number. for example [0000] [0000] [0001] [1011] sometimes numbers are misinterpreted as negative numbers and simetimes as zero!
让我给你一个直观的例子:
let me give you an intuitive example:
char s_num[4] = {120, 80, 40, 1};
int t_num = 0;
t_num = int(s_num);
我希望我能很好地解释我的问题!
I wish I could explain my problem well!
如何将这样的数组转换为单个整数值?
how can i cast such arrays into a single integer value?
ok ok ok,让我改一下代码以便更好地解释:
ok ok ok, let me change my code to explain it better:
char s_num[4] = {0, 0, 0, 13};
int t_num;
t_num = *((int*) s_num);
cout << "t_num: " << t_num << endl;
这里我们必须得到 13 作为结果,好吗?但是再次使用这个新解决方案,答案是错误的,您可以在您的计算机上进行测试!我得到这个号码:218103808 这绝对是错误的!
here we have to get 13 as the result, ok? but again with this new solution the answer is wrong, you can test on your computers! i get this number:218103808 which is definitely wrong!
推荐答案
你将 (char*) 转换为 (int).你应该做的是将指针转换为整数,即
You cast (char*) to (int). What you should do is cast to pointer to integer, i.e.
t_num = *((int*) s_num));
但实际上你应该将你的代码提取到它自己的函数中并确保:
But really you should extract your code into it's own function and make sure that:
- 字节序正确
sizeof(int) == 4
- 使用 C++ 类型转换(即
static、dynamic、const、reinterpret
)
相关文章