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

Converting byte value into integer and vice versa

Hello,

I need to know how the get the integer value of a byte and vice versa.

I want to get the integer value from a byte read from a binary file.
I also want to convert the integer value back into a byte value for write.

Below I have code where the current byte is read into the variable 'byte". I am basically copying one file to the other.

Thanks.

#include <fstream.h> 
#include <iomanip.h> 
int main() 
{ 
int ind, tot; 
unsigned char byte; 
ifstream infile("inputfile.dat", ios::in | ios::binary); 
ofstream outfile("outputfile.dat", ios::binary ); 

for (!infile) 
{ 
infile.read( byte, 1 ); 
outfile.write( byte, 1 ); 
return 0; 
} 

}
newstar_water
Newbie Poster
1 post since Aug 2003
Reputation Points: 11
Solved Threads: 0
 

#include
#include
int main()
{
int ind, tot;
unsigned char byte;

ifstream infile("inputfile.dat", ios::in | ios::binary);
ofstream outfile("outputfile.dat", ios::binary );

for (!infile)
{
int iVal;
unsigned char ucVal;

infile.read( byte, 1 );

//this code I test with Visual C++.

//convert unsigned char to integer
iVal = (int)byte; //int cast

//convert integer value to unsigned char
ucVal = (unsigned char)iVal; //cast to unsigned char

outfile.write( byte, 1 );

return 0;
}

}

fzoff
Newbie Poster
2 posts since Sep 2003
Reputation Points: 11
Solved Threads: 0
 

for ex.
string s = "0x31"

i want to convert the string into a byte value...say store in char c.
so i print c...it would display "1".
How to do this?

iadman
Newbie Poster
2 posts since Jul 2010
Reputation Points: 9
Solved Threads: 0
 

Hello,

I need to know how the get the integer value of a byte and vice versa.

As the first respondent answered inunformatted code, it's as simple as a cast. I would additionally point out that it is useful to understand the type system in c++.

There are several integer types. These include

char
unsigned char
short
unsigned short
int
unsigned int
long
unsigned long

All of these types may be cast between each other directly.

dusktreader
Posting Whiz in Training
259 posts since Jan 2010
Reputation Points: 152
Solved Threads: 41
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You