Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cast an array of char into a single integer number?

i'm trying to read contents of PNG file.

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].

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

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!

like image 669
sepisoad Avatar asked Jan 08 '11 09:01

sepisoad


People also ask

How do I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

Can you cast a char to an int in c?

There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()

Can you put a char in an int array?

As others have mentioned, char will be promoted to int when you assign elements of the int[] array with char values. You would have to use an explicit cast when you are reading from that array. int a[10]; char c='X'; a[0] = c; c = (char) a[0];

How do I convert a number to a char array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.


1 Answers

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:

  1. endianness is correct
  2. sizeof(int) == 4
  3. Use C++ casts (i.e. static, dynamic, const, reinterpret)
like image 192
Axel Avatar answered Oct 31 '22 14:10

Axel