如何将char数组转换为单个整数? [英] how to cast an array of char into a single integer number?

查看:159
本文介绍了如何将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 *到整数,我得到错误的数字。例如
有时数字被错误地解释为负数并且时间为零!

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, 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!

推荐答案

you cast(char *)to(int)。你应该做的是将指针转换为整数,例如这样:

you cast (char*) to (int). What you should do is cast to pointer to integer, ie something like this:

t_num = *((int*) s_num));

但你真的应该把你的代码提取到自己的函数中,并确保

But really you should extract your code into it's own function and make sure that


  1. 字元序列正确

  2. sizeof(int)== 4

  3. 新C ++类型

这篇关于如何将char数组转换为单个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆