473,881 Members | 1,647 Online
Bytes | Software Development & Data Engineering Community
+ 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 14467
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...@com Acast.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_ist ream<_Elem,_Tra its>::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: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*******@rocke tmail.com
Jun 27 '08 #6
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@com Acast.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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #7
On 16 mai, 23:16, "Jim Langston" <tazmas...@rock etmail.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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #8
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 #9
James Kanze wrote:
On 16 mai, 20:43, Victor Bazarov <v.Abaza...@com Acast.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 #10

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

Similar topics

4
16478
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 someone can help Thanks
1
3952
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 I can get around everything but one stumbling point I would like some advice on. The win api uses an unsigned char array for writing binary data to and from the gds file. Now, one reason I want standards compliant code is to be able to run my...
20
3089
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: --cut here-- typedef struct pkg_ { short int info; char* data;
11
24184
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 memchr(), memcmp(), memmove() a lot. Is there an ANSI C maximium size for character arrays which are guaranteed to succeed, assuming the machine has sufficient memory? And will the memxxx() functions work with that size? I'm looking at hopefully...
8
3682
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 from that string, the continment is altered from it's original state. Below is a code snipped I'm using: // Here I read the wave file and I convert the result to a string byte b = new byte; FileStream fs = File.OpenRead("test.wav"); int size =...
33
3692
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 has prepared for those who love him" 1 Cor 2:9
3
3700
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 understanding how to properly convert the bit/pixel in pbm to byte/pixel in pgm. My program is very straight forward conceptually open files, read header, read binary data, convert to p5 in loop and then write file out. My for loop is where I am...
2
4386
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. The binary data is how they send numbers (they call it "Big Endian"). I only know at run time whether a byte is going to be text or binary (one of the fields I decode tells me which the latter fields are). The code I have converts a single byte of...
11
3830
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 doesn't seem to work. The code below is what I'm trying to use. Anyone see any obvious errors? or have any hints/pointers? regards, Igor float floatRead = 0;
0
9927
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9776
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10814
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7109
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
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 we have to send another system
2
4196
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.