954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Conversion from char to decimal(int)

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.

eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

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));
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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) ;
eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

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

}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
>>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,

eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You