1

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

}
4
Contributors
3
Replies
6
Views
13 Years
Discussion Span
Last Post by dusktreader
1
#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) 
{ 
    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; 
} 

}

Edited by Dani: Formatting fixed

-2

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?

Edited by iadman: n/a

Comments
Start your own thread, don't hijack someone else's
0

Hello,

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

As the first respondent answered in unformatted 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.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.