I've read 4 consecutive bytes from a binary file, and store the value as follows,

int main()
{
char next4[4] ; 

while(!fileopen.eof())
{
        fileopen.read (next4, 4 ) ;
}

}

What I want to do is, that value in next4 want to convert into a decimal/int value. How can I do that. Search on MSDN and unable to find a clear explanation.

you could have read it directly into the integer

long next4;
 fileopen.read (&next4, sizeof(long) ) ;

or you can use the assignment statement

int main()
{
char next4[4] ; 
int num;
while(!fileopen.eof())
{
        fileopen.read (next4, 4 ) ;
        num = *(int *)next4;
}

}

A third way is to use memcpy() to copy the data

int num;
...
memcpy(&num, next4, sizeof(long));

Thanks,

What is the wrong with this code.

char_traits<char>::char_type ch = next4[4] ;
char_traits<char>::int_type int_val ;
int_val = char_traits<char>::to_int_type (ch) ;

>>What is the wrong with this code
Nothing that I know of, other than it doesn't work :) This produces the wrong value, probably because line 10 is only one byte of a 4-byte number.

#include <iostream>
#include <string>
using namespace std ;

int main()
{
    char next4[4] = {0};
    int n = 123;
    memcpy(next4, &n, sizeof(int));
    char_traits<char>::char_type ch = next4[4] ;
    char_traits<char>::int_type int_val ;
    int_val = char_traits<char>::to_int_type (ch) ;

    cout << "int_val = " << int_val << "\n";
    return 0;

}

>>What is the wrong with this code
Nothing that I know of, other than it doesn't work :) This produces the wrong value, probably because line 10 is only one byte of a 4-byte number.

Thanks, I got the point and stuck with this whole night. When I use it only on byte count there in my code.

Thanks again,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.