473,241 Members | 1,905 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

Doing things the hard way...accessing an array as different data types

I have a feeling that I'm doing things all ass-backwards (again ;-),
and would like some advice. What I want to do is:

put some data to memory and then access that memory space as an array
of data-types of my choosing (eg an array of char, short, or int).

The application has to do with generating checksum-type values for
files or strings, so speed is important, as I just want to quickly get
this value then move on to the next task. As such, I don't want to
"properly" bit-shift bytes to ints...rather, I want to put all the
bits in sequential order then access them in chunks sized to the
machine's native integer for bitwise operations.

I had been doing this by using the fstream write() function to dump
the file to a char array (on the heap sized to filesize), then casting
the char array to an int*. This worked fine, but then I learned about
potential alignment problems...that there could be cases that the
location of the char* might be an invalid location for an int*. To
circumvent this potential problem, I made a class, align_int, that
reverses the order...first creating the int array, then casting the
array to a char*, then dumping the file to the char*. This works
because every int* address is accessable as a char*, even though some
char* addresses may NOT be accessable as an int*.

So...now I've got my big, ugly, class that offers pointers of every
native int type to the same memory-space...and it works fine...but I
realize that the class contains pointers that are never used on any
given run. I'm wondering if there's an easier way to do this using a
single void* cast to the proper type as the return value of getter
member functions?

What I need from the class is the ability to request a pointer to the
file as any of the integer data-types. My dumb-ass class follows...

//AlignInt_class.h
#include <string>

class AlignInt{
private:
bool fileOKd(std::string filespec);
void load_file();
std::string type;

public:
AlignInt();
~AlignInt();

void loadfile(std::string filespec);
void loadstring(std::string stringin);
void prealigned(unsigned long* parray, unsigned int byte_len);

unsigned int* ui;
unsigned long* ul;
unsigned short* us;
unsigned char* uc;
int* i;
long* l;
short* s;
char* c;

std::string filespec;
unsigned int len_c; // len of file in bytes (char)
unsigned int len_s; // len of file in shorts
unsigned int len_i; // len of file in int
unsigned int len_l; // len of file in long
bool ok;
void verify();
};

//alignint.cpp
#include "AlignInt_class.h"
#include <iostream>
#include <fstream>

using namespace std;

AlignInt::AlignInt(){
ok = 0;
}

AlignInt::~AlignInt(){
if(ok) delete[] ul;
}

void AlignInt::loadfile(string filename){
if(ok) cout << "ERROR...memory redesignation ERROR 1" << endl;
else{
filespec = filename;
ok = fileOKd(filespec);
if(ok){
load_file();

//ul....defined in load_file
uc = reinterpret_cast<unsigned char*>(ul);
ui = reinterpret_cast<unsigned int*>(ul);
us = reinterpret_cast<unsigned short*>(ul);
i = reinterpret_cast<int*> (ul);
l = reinterpret_cast<long int*> (ul);
s = reinterpret_cast<short int*> (ul);
//c....defined in load_file

// len_c....defined in load_file
// len_l....defined in load_file
len_i = len_l * (sizeof(long int)/sizeof(unsigned int));
len_s = len_l * (sizeof(long int)/sizeof(unsigned short
int));
type = "file";
}else cout << "FILE ERROR: Cannot load: " << filespec << endl;
}
}

void AlignInt::load_file(){
int wordsize = sizeof(unsigned long int);
ifstream in (filespec.c_str(), ios::in | ios::binary);
in.seekg(0, ios::end);
len_c = in.tellg(); // file length in bytes
len_l = (len_c / wordsize) + ((len_c % wordsize) > 0);
//^^^adds one if remainder^^^//
ul = new unsigned long int[len_l];
ul[len_l - 1] = 0; //make sure last byte is cleared before
putting file in array
c = reinterpret_cast<char*>(ul);

in.seekg(0, ios::beg);
in.read(c, len_c);
in.close();
}

void AlignInt::loadstring (string stringin){
if(ok) cout << "ERROR...memory redesignation ERROR 2" << endl;
else{
int wordsize = sizeof(unsigned long int);
len_c = stringin.size();
len_l = (len_c / wordsize) + ((len_c % wordsize) > 0);
ul = new unsigned long int[len_l];
ul[len_l - 1] = 0;
c = reinterpret_cast<char*>(ul);
for(unsigned int j = 0; j < len_c; ++j)
c[j] = stringin[j];

uc = reinterpret_cast<unsigned char*>(ul);
ui = reinterpret_cast<unsigned int*>(ul);
us = reinterpret_cast<unsigned short*>(ul);
i = reinterpret_cast<int*> (ul);
l = reinterpret_cast<long int*> (ul);
s = reinterpret_cast<short int*> (ul);
len_i = len_l * (sizeof(long int)/sizeof(unsigned int));
len_s = len_l * (sizeof(long int)/sizeof(unsigned short int));

ok = true; //string is in memory
type = "string";
}
}

void AlignInt::prealigned(unsigned long* parray, unsigned int
byte_len){
if(!ok){ //ok must == 0
int wordsize = sizeof(unsigned long int);
ul = parray;
len_c = byte_len;
len_l = (len_c / wordsize) + ((len_c % wordsize) > 0);
uc = reinterpret_cast<unsigned char*>(ul);
ui = reinterpret_cast<unsigned int*>(ul);
us = reinterpret_cast<unsigned short*>(ul);
i = reinterpret_cast<int*> (ul);
l = reinterpret_cast<long int*> (ul);
s = reinterpret_cast<short int*> (ul);
c = reinterpret_cast<char*>(ul);
len_i = len_l * (sizeof(long int)/sizeof(unsigned int));
len_s = len_l * (sizeof(long int)/sizeof(unsigned short int));
type = "prealigned array";
}else cout << "ERROR...memory redesignation ERROR 3";
}

bool AlignInt::fileOKd(string filespec){
ifstream in(filespec.c_str());
return in.good();
}
void AlignInt::verify(){
cout << "Verifying...\n"
<< "The " << type
<< " Contains " << len_c << " chars\n"
<< "Fits into an array of " << len_s << " short int\n"
<< "Fits into an array of " << len_i << " int\n"
<< "Fits into an array of " << len_l << " long int\n\n"
<< "The following should all point to the same memory
space\n"
<< "p ulong " << ul << "\n"
<< "p long " << l << "\n"
<< "p uint " << ui << "\n"
<< "p int " << i << "\n"
<< "p short " << s << "\n"
<< "p ushort " << s << "\n"
<< "p uchar " << reinterpret_cast<unsigned int*>(uc) <<
"\n"
<< "p char " << reinterpret_cast<int*>(c) << endl;
}
Jul 22 '05 #1
1 2042
"J. Campbell" <ma**********@yahoo.com> wrote...
[...]

So...now I've got my big, ugly, class that offers pointers of every
native int type to the same memory-space...and it works fine...but I
realize that the class contains pointers that are never used on any
given run. I'm wondering if there's an easier way to do this using a
single void* cast to the proper type as the return value of getter
member functions?

What I need from the class is the ability to request a pointer to the
file as any of the integer data-types. My dumb-ass class follows...


Perhaps a template function that casts a pointer that you have stored
into the required pointer type is better?

class Blah {
...
char* stored_pointer;
public:
template<class U> U* get_pointer_to_()
{
return static_cast<U*>(stored_pointer);
}
};

...

Blah blah;
...
int *ptr = blah->get_pointer_to_<int>();

Here you will only store one pointer, and only generate the casts
to the types used in the program...

Now, you still have to make sure your 'stored_pointer' is aligned
properly, but you've already solved this one, right?

Victor

Jul 22 '05 #2

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

Similar topics

2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
6
by: Chris Styles | last post by:
Dear All, I've been using some code to verify form data quite happily, but i've recently changed the way my form is structured, and I can't get it to work now. Originally : The form is...
38
by: VK | last post by:
Hello, In my object I have getDirectory() method which returns 2-dimentional array (or an imitation of 2-dimentional array using two JavaScript objects with auto-handled length property - please...
18
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the...
0
by: sonu | last post by:
I have following client side code which i have used in my asp.net project SummaryFeatured Resources from the IBM Business Values Solution Center WHITEPAPER : CRM Done Right Improve the...
7
by: Tomás | last post by:
Okay firstly I'll start with pointers. I have always thought of a pointer as storage which holds a memory address, plain and simple. Let's say that on a particular platform, an "int" is 32-Bit, and...
5
by: pt | last post by:
Hi, i am wonderng what is faster according to accessing speed to read these data structure from the disk in c/c++ including alignment handling if we access it on little endian system 32 bits...
17
by: Ben Bacarisse | last post by:
candide <toto@free.frwrites: These two statements are very different. The first one is just wrong and I am pretty sure you did not mean to suggest that. There is no object in C that is the...
6
by: r035198x | last post by:
I have put together this article to give people starting Swing an awareness of issues that need to be considered when creating a Swing application. Most of the Swing tutorials that I have seen just...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.