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!
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.
There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()
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];
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.
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
static, dynamic, const, reinterpret
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With