GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 20-Jul-2008, 11:04
transfrank transfrank is offline
Junior Member
 
Join Date: Aug 2007
Posts: 70
transfrank will become famous soon enough

Convert from FILE .read()char array to integer array


Hello,
I have data retrieved from .read() file i/o operations which works on char arrays. I'm looking
at cleaner ways to convert into arrays of 16 bit and 32 bit unsinged integers.

One way to do it is :
CPP / C++ / C Code:
myFile.read( reinterpret_cast<char *> pShortIntegerArray, qty_of_short_ints*2)
myFile.read( reinterpret_cast<char *> pLongIntegerArray, qty_of_long_ints*4)
I am trying to avoid coding with C arrays where I can write past boundaries. Is there a better C++ way?

Another question is that if I encapsulate the .read into a function that outputs with C++ strings,
is there an easy way to do the same thing, i.e. convert from the char array to shor int arrays?
  #2  
Old 20-Jul-2008, 12:48
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Convert from FILE .read()char array to integer array


Quote:
Originally Posted by transfrank
I have data retrieved from .read() file i/o operations which works on char arrays. I'm looking
at cleaner ways to convert into arrays of 16 bit and 32 bit unsinged integers.
The signature is fixed. If it expects a character array as an argument, you have to provide a character array.
Quote:
I am trying to avoid coding with C arrays where I can write past boundaries. Is there a better C++ way?
You may want to look at the string class. eg.
CPP / C++ / C Code:
string s;
cin >> s;
  #3  
Old 20-Jul-2008, 13:38
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Convert from FILE .read()char array to integer array


Quote:
Originally Posted by transfrank
I am trying to avoid coding with C arrays where I can write past boundaries. Is there a better C++ way?
The "better C++ way" is not to use arrays. Use vectors. (Read a value. Push it. Read a value. Push it. Etc.)
See Footnote.

I assume that your file contains binary data. If not, then there's not much point in using the istream read() function, right? I mean, if you want to read integer values from a text file, just use ">>" to read the formatted data. (Still using vectors to hold the values, not arrays.)

Anyhow for binary files:

CPP / C++ / C Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    cout << "sizeof(short) = " << sizeof(short) << endl;
    vector<short> vs;
    short x;
    char *inname = "sfile.bin";
    ifstream infile(inname, ios::binary);
    if (!infile) {
        cout << "Couldn't open file " << inname << " for reading." << endl;
        return EXIT_FAILURE;
    }
    cout << "Opened file " << inname << " for reading." << endl;
    unsigned bytes_read = 0;
    while (infile.read(reinterpret_cast<char *>(&x), sizeof(x))) {
        vs.push_back(x);
        bytes_read += infile.gcount();
    }
    cout << "Number of bytes  read from the file = " << bytes_read << endl;
    cout << "Number of shorts read from the file = " << vs.size() << endl;
    for (unsigned i = 0; i < vs.size(); i++) {
        cout << "vs[" << i << "] = 0x" 
             << setfill('0') << setw(sizeof(short))
             << hex << vs[i] 
             << " (" 
             << setfill(' ') << dec << setw(6) 
             << vs[i] << " decimal)" << endl;
    }
    infile.close();

    return EXIT_SUCCESS;
}

I have attached a zipped binary file for testing. The file contains hex bytes
Code:
12 34 56 78 9a bc de f0

Here's the output:

Code:
sizeof(short) = 2 Opened file sfile.bin for reading. Number of bytes read from the file = 8 Number of shorts read from the file = 4 vs[0] = 0x3412 ( 13330 decimal) vs[1] = 0x7856 ( 30806 decimal) vs[2] = 0xbc9a (-17254 decimal) vs[3] = 0xf0de ( -3874 decimal)

As you can see, on my system shorts are two bytes long and internal storage is little-endian.
Quote:
Originally Posted by transfrank
Another question...
What the heck are you asking? What do you have and what to you want to convert it to? Could you give an example?

(If I had a numeric variable and I wanted to convert its value to a C++ string, I would probably use a stringstream object, but I'm not sure that's what you have in mind.)

Regards,

Dave

Footnote: If you really, really need to use arrays rather than C++ vectors (and there are times when you may have to do this), then the way to keep from writing past the end of the arrays is to create code that doesn't write past the end of the arrays. I know this sounds silly and maybe even a little sarcastic, but I mean no disrespect. It is the programmer's duty to make sure the code he/she writes can never, ever write past the end of the arrays.
Attached Files
File Type: zip sfile.bin.zip (158 Bytes, 21 views)
Last edited by davekw7x : 20-Jul-2008 at 15:02.
  #4  
Old 21-Jul-2008, 14:54
transfrank transfrank is offline
Junior Member
 
Join Date: Aug 2007
Posts: 70
transfrank will become famous soon enough

Re: Convert from FILE .read()char array to integer array


davekw7x,
Thanks very much for the vector advice.
Quote:
It is the programmer's duty to make sure the code he/she writes can never, ever write past the end of the arrays.
Earlier this year, I made an array class with the [] operator and messages that pop up if I try to write past the boundaries. The vectors look like a clean already existing method.
Quote:
What the heck are you asking?
There are 2 goals.

GOAL A) is to not use arrays at all nowhere in my code. Even with my integer class, I had to do the intermediate pass with arrays sometimes.

GOAL B) is to get rid of the amateurish way to take 4 chars (usually as subsets of C++ strings), do the sign checking and create an unsigned 32 bit integer. (also the same with the 16 bit short ints)

You see I have packets where in a function I process the header and footer, leaving the middle payload for another function to process as a C++ string. This payload has the 32 and 16 bit arrays I was talking about and am exploring neater ways to do this. Not all my packets have the same size of 16 bit arrays. Maybe I could use a few structs for the couple packet sizes.

Off the top of your head, do you see another solution for goal B???
Thanks a lot!
Frank
  #5  
Old 22-Jul-2008, 01:19
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Convert from FILE .read()char array to integer array


Quote:
Originally Posted by transfrank

GOAL A) is to not use arrays at all nowhere in my code.
Well, I have seen it written that some people think that arrays are always evil. I feel that there are times when they are appropriate and even desirable, and times when other things (C++ STL objects like vectors, sets, maps, lists, queues, etc.) are The Way To Go. (Your Mileage May Vary.) Believe it or not, it is possible to write a bad program with vectors, too.

Quote:
Originally Posted by transfrank
GOAL B) is to get rid of the amateurish way to take 4 chars (usually as subsets of C++ strings), do the sign checking and create an unsigned 32 bit integer. (also the same with the 16 bit short ints)
I still don't know what you mean. What "amateurish" way? I showed how to get bytes from a binary file into memory (actually, I used your file read() example, and I don't see anything particularly amateurish about it).

If you know that the bytes are in correct order, (file-endianness is the same as machine-endianness), then you are through, as I showed in the printout. If the bytes must be reversed, then reverse them. So: What's the question? (But I asked that already.) There's no "sign checking or other "creation." They simple are in memory assigned to a particular variable.
Quote:
Originally Posted by transfrank
You see I have packets where in a function I process the header and footer, leaving the middle payload for another function to process as a C++ string.
If you are thinking of a file or a network packet as an array of bytes (chars), note that an array of chars is not a string. Not in C. Not in C++. The bytes mean whatever you have defined them to mean. Four bytes in a row can be a 32-bit integer. Even if they are four ASCII chars, that still doesn't necessarily mean that they are a string. (The first four bytes of a .wav file are 0x52, 0x49, 0x46, 0x46, which are ASCII for "RIFF", but they are not a string. Not a C string. Not a C++ string. They are just four bytes. The next four bytes are a 32-bit unsigned int (in little-endian format) They represent the number of bytes in the file after those first eight. There is not a single "string" in a standard .wav file.

Read the bytes from the file into wherever the heck you want them to go. If they are binary numerical values and the bytes in the are in the correct order for your machine, then read them into a variable of the correct type (length). If your program has to read bytes from a file or a network packet (you always have to know whether the ints were written in big-endian order or little-endian order) you can create code that reads a byte at a time into a numeric variable of correct size (using logical shift and "OR" operations) and store in whatever endianness is natural for your machint. In other words the same source code will work whether it is compiled on a big-endian machine or a little-endian machine.

Network programmers use functions like htonl(), htons() to do it in a way that is more-or-less invisible to programmers. Compiler configuration by the vendor has already taken into account whether the bytes going between machine and network need to be reversed. These and many other functions used in sockets programming are not standard C or C++ library functions, but are (almost) always supplied with serious compilers.
Quote:
Originally Posted by transfrank
This payload has the 32 and 16 bit arrays I was talking about and am exploring neater ways to do this. Not all my packets have the same size of 16 bit arrays. Maybe I could use a few structs for the couple packet sizes.
Use of structs is an implementation detail (like headers defined with various parameters for bitmap files or waveform files). If the headers are structured in a defined way, then use a struct to make program documentation easier (and the code can look neater, but it's not automatically neater---it depends on you). For example, it's easier to call functions that use pointers to structs as arguments rather than a long list if individual numeric arguments.

Regards,

Dave

Footnote: The subject of endianness must always be taken into account whenever you are dealing with binary multi-byte numeric data items. If you are making your own network protocol, use whatever you want, but you should be aware that all significant network standards transfer bytes in big-endian fashion. That means for people using Intel/AMD PCs (and all of the other little-endian systems out there) always have to reverse byte order when transmitting or receiving multi-byte binary numeric data.
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Power Calibration Error In Nero Fix (hopefully) matt3678 Computer Hardware Forum 60 20-Aug-2009 06:04
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 08:44
After execution - Error cannot locate /Skin File? WSCH C++ Forum 1 05-Mar-2005 21:03
[Tutorial] Standard I/O aaroncohn C Programming Language 20 27-Feb-2004 22:07

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 08:27.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.