473,493 Members | 4,355 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

converting char to int (reading from a binary file)

Hi,
I'm trying to read some binary data from a file, I've read a few bytes
of the data into a
char array with ifstream. Now I know that the first 4 bytes in the
char array represent
an integer. How do I go about converting the elements to an integer?
regards, Igor
Jun 27 '08 #1
15 14431
basically:

int i = *( ( int * )ptr )
Jun 27 '08 #2
sebastian wrote:
basically:

int i = *( ( int * )ptr )
That is a very bad idea, 'ptr' may not be correctly aligned. It would
be much better to supply the address of 'i' to the procedure that reads
the bytes, something like

int i = 0;
myfile.read(&i, sizeof(int));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #3
On May 16, 8:43 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
sebastian wrote:
basically:
int i = *( ( int * )ptr )

That is a very bad idea, 'ptr' may not be correctly aligned. It would
be much better to supply the address of 'i' to the procedure that reads
the bytes, something like

int i = 0;
myfile.read(&i, sizeof(int));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
thanks for your response. I'm not 100% sure I understand what you mean
by correctly aligned, would you mind clarifying? I also can't get your
code snippet to work; I get the following compile error:

"Error 1 error C2664: 'std::basic_istream<_Elem,_Traits>::read' :
cannot convert parameter 1 from 'int' to 'char *' "

kind regards,
Igor
Jun 27 '08 #4
On May 16, 8:36 pm, sebastian <sebastianga...@gmail.comwrote:
basically:

int i = *( ( int * )ptr )
thanks for your response, it does the trick...
Igor
Jun 27 '08 #5
itdevries wrote:
On May 16, 8:43 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>sebastian wrote:
>>basically:
int i = *( ( int * )ptr )
That is a very bad idea, 'ptr' may not be correctly aligned. It would
be much better to supply the address of 'i' to the procedure that reads
the bytes, something like

int i = 0;
myfile.read(&i, sizeof(int));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

thanks for your response. I'm not 100% sure I understand what you mean
by correctly aligned, would you mind clarifying?
On some hardware objects of certain sizes (like 'int') need to exist in
memory at addresses with certain properties, like divisible by the size
of the object, for example. In such systems a 'char' can lie on the odd
byte boundary, which may not necessarily be acceptable for an 'int' that
need an address divisible by, say, 4. Attempt to access the object (by
dereferencing the pointer formed by casting a pointer to char) can
trigger a hardware exception.
I also can't get your
code snippet to work; I get the following compile error:

"Error 1 error C2664: 'std::basic_istream<_Elem,_Traits>::read' :
cannot convert parameter 1 from 'int' to 'char *' "
You probably missed the '&'. Also, to convert a pointer to 'int' to a
pointer to 'char' you may need to use 'reinterpret_cast' (which I didn't
use).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #6
On May 16, 9:50 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
itdevries wrote:
On May 16, 8:43 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
sebastian wrote:
basically:
int i = *( ( int * )ptr )
That is a very bad idea, 'ptr' may not be correctly aligned. It would
be much better to supply the address of 'i' to the procedure that reads
the bytes, something like
int i = 0;
myfile.read(&i, sizeof(int));
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
thanks for your response. I'm not 100% sure I understand what you mean
by correctly aligned, would you mind clarifying?

On some hardware objects of certain sizes (like 'int') need to exist in
memory at addresses with certain properties, like divisible by the size
of the object, for example. In such systems a 'char' can lie on the odd
byte boundary, which may not necessarily be acceptable for an 'int' that
need an address divisible by, say, 4. Attempt to access the object (by
dereferencing the pointer formed by casting a pointer to char) can
trigger a hardware exception.
I also can't get your
code snippet to work; I get the following compile error:
"Error 1 error C2664: 'std::basic_istream<_Elem,_Traits>::read' :
cannot convert parameter 1 from 'int' to 'char *' "

You probably missed the '&'. Also, to convert a pointer to 'int' to a
pointer to 'char' you may need to use 'reinterpret_cast' (which I didn't
use).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Victor,
Many thanks for taking the time to explain!
I think I understand what you're saying, do you know what the chances
are of this happening
on a win32 platform?
regards,
Igor
Jun 27 '08 #7
itdevries wrote:
On May 16, 8:36 pm, sebastian <sebastianga...@gmail.comwrote:
>basically:

int i = *( ( int * )ptr )

thanks for your response, it does the trick...
Igor
Be aware that depending on your OS this may break at times, not at others,
or always work. It depends on your OS mainly and if it requires intergers
to by specifcally byte aligned. I know that this will work on Windows
systems fine. I understand that wrong alignment it will break on Sun
systems.

If this is platform specific for you and you will never run it on another
platform and you're sure that your system won't break on byte misalligned
integers it should be fine to use. If you ever plan on running the code on
another system then you'll need to do it another way.
--
Jim Langston
ta*******@rocketmail.com
Jun 27 '08 #8
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@comAcast.netwrote:
sebastian wrote:
basically:
int i = *( ( int * )ptr )
That is a very bad idea, 'ptr' may not be correctly aligned.
Not to mention issues of size and representation. (As an
extreme case, I know of one machine which uses 6 byte signed
magnitude ints.)

The original poster didn't begin to give enough information with
regards to the input format for us to say, but if it's a
standard Internet protocol, then you read an int with something
like:

int32_t
getInt( std::istream& source )
{
uint32_t result = source.get() << 24 ;
result |= source.get() << 16 ;
result |= source.get() << 8 ;
result |= source.get() ;
return result ;
}

Except that you'd add some error handling. (And of course, if
you don't have int32_t and uint32_t---which are only present if
the hardware supports them directly, then the conversion from
unsigned to signed becomes more difficult as well.)
It would be much better to supply the address of 'i' to the
procedure that reads the bytes, something like
int i = 0;
myfile.read(&i, sizeof(int));
That doesn't work any better, really.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
On 16 mai, 23:16, "Jim Langston" <tazmas...@rocketmail.comwrote:
itdevries wrote:
On May 16, 8:36 pm, sebastian <sebastianga...@gmail.comwrote:
basically:
int i = *( ( int * )ptr )
thanks for your response, it does the trick...
Be aware that depending on your OS this may break at times,
not at others, or always work. It depends on your OS mainly
and if it requires intergers to by specifcally byte aligned.
I know that this will work on Windows systems fine. I
understand that wrong alignment it will break on Sun systems.
If this is platform specific for you and you will never run it
on another platform and you're sure that your system won't
break on byte misalligned integers it should be fine to use.
If you ever plan on running the code on another system then
you'll need to do it another way.
It will also fail on an Intel if the int's are in the standard
Internet format. In general, you can only count on it working
if you are reading and writing from the same run of the same
program---I've seen cases where just recompiling with a newer
version of the compiler made it fail.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #10
itdevries wrote:
[..]
I think I understand what you're saying, do you know what the chances
are of this happening
on a win32 platform?
Even if I did, we refrain from discussing platform-specific issues
here. Consider asking about it in the newsgroup for Win32 or for
your compiler. Best of luck!

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #11
James Kanze wrote:
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@comAcast.netwrote:
> int i = 0;
myfile.read(&i, sizeof(int));

That doesn't work any better, really.
Do tell.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #12
That doesn't work any better, really.

that's because istream::read expects a pionter to char (you must cast
it). but as others have already pointed out, there are many problems
with these sorts of casts. there are serialization libraries available
(such as boost::serialize) designed specifically for this purpose, in
case you really want to get the job done right...
Jun 27 '08 #13
On May 16, 5:26*pm, sebastian <sebastianga...@gmail.comwrote:
That doesn't work any better, really.

that's because istream::read expects a pionter to char (you must cast
it). but as others have already pointed out, there are many problems
with these sorts of casts. there are serialization libraries available
(such as boost::serialize) designed specifically for this purpose, in
case you really want to get the job done right...
I agree B.Ser will produce correct results in this case, but it may
not
produce those results efficiently - http://webEbenezer.net/comparison.html

Brian Wood
Ebenezer Enterprises
www.webEbenezer.net
Jun 27 '08 #14
On 17 mai, 01:01, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
James Kanze wrote:
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@comAcast.netwrote:
int i = 0;
myfile.read(&i, sizeof(int));
That doesn't work any better, really.
Do tell.
Do tell what? To begin with, it won't compile without a
reinterpret_cast (which is a very good sign that something is
wrong with it). And it still ignores all issues of size and
representation.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #15
On May 16, 11:31 pm, James Kanze <james.ka...@gmail.comwrote:
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@comAcast.netwrote:
sebastian wrote:
basically:
int i = *( ( int * )ptr )
That is a very bad idea, 'ptr' may not be correctly aligned.

Not to mention issues of size and representation. (As an
extreme case, I know of one machine which uses 6 byte signed
magnitude ints.)

The original poster didn't begin to give enough information with
regards to the input format for us to say, but if it's a
standard Internet protocol, then you read an int with something
like:

int32_t
getInt( std::istream& source )
{
uint32_t result = source.get() << 24 ;
result |= source.get() << 16 ;
result |= source.get() << 8 ;
result |= source.get() ;
return result ;
}

Except that you'd add some error handling. (And of course, if
you don't have int32_t and uint32_t---which are only present if
the hardware supports them directly, then the conversion from
unsigned to signed becomes more difficult as well.)
It would be much better to supply the address of 'i' to the
procedure that reads the bytes, something like
int i = 0;
myfile.read(&i, sizeof(int));

That doesn't work any better, really.

--
James Kanze (GABI Software) email:james.ka...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Hi James,
thanks for taking the time to respond, I really appreciate it.

The code is intended to read data from a file generated by a fortran
program
and only ever will be run on windows machines. I don't need a mega
portable/robust app, just need a program that will extract data for a
particular
version of the file. If it runs on windows 2k/xp/vista for most
processors then that's
good enough for the time being. At this point I prefer not to make
life too
difficult for myself and would prefer to use the typecasting trick
proposed
by sebastian. Do you think that it's safe "enough"?

As an added difficulty the fortran file is "record" oriented not
"stream" oriented
(i don't know if I'm using the right official terminology) which means
that
there's some peculiarity about how I have to read the data; some
records
contain only one int, others contain more. Since all the records are
4*4 bytes long
it means I have to skip around over empty records/control info to read
everything.

kind regards,
Igor
Jun 27 '08 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
16442
by: Joseph Suprenant | last post by:
I have an array of unsigned chars and i would like them converted to an array of ints. What is the best way to do this? Using RedHat 7.3 on an Intel Pentium 4 machine. Having trouble here, hope...
1
3940
by: glen_stark | last post by:
Hi. I have code for reading and writing gds files that I have inherited from a company and need to make standards compliant. Unfortunately the code is heavily dependant on the win api. I think...
20
3011
by: ishmael4 | last post by:
hello everyone! i have a problem with reading from binary file. i was googling and searching, but i just cant understand, why isnt this code working. i could use any help. here's the source code:...
11
23963
by: Walter Dnes (delete the 'z' to get my real address | last post by:
I've noticed a few threads (full of sound and fury, signifying nothing) here recently about allocation of large memory blocks. I'm about to start on a personal pet project where I'll be using...
8
3651
by: Marius Cabas | last post by:
Hi, I'm a beginner so don't shoot ;) I'm reading a wave file into a byte and I'm trying to convert the result to String but the converted string is altered, so if I'm generating a new wave file...
33
3628
by: Jordan Tiona | last post by:
How can I make one of these? I'm trying to get my program to store a string into a variable, but it only stores one line. -- "No eye has seen, no ear has heard, no mind can conceive what God...
3
3666
by: Howler | last post by:
Hello all, I am having a hard time seeing what I am doing wrong with a program I am having to write that converts pbm monochrome images into a similar pgm file. The problem I am having is...
2
4343
by: DBuss | last post by:
OK, I'm reading a multicast socket. It attaches fine, reads fine, all of that. The problem is that while some of the data I get is normal text (ASCII String), some of it is Binary Integer. ...
11
3777
by: itdevries | last post by:
Hi, I'm trying to convert some char data I read from a binary file (using ifstream) to a float type. I've managed to convert the int types but now I need to do the float types as well but it...
0
6980
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6862
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7364
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4886
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3087
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1397
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
282
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.