473,756 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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::st ring filespec);
void load_file();
std::string type;

public:
AlignInt();
~AlignInt();

void loadfile(std::s tring filespec);
void loadstring(std: :string stringin);
void prealigned(unsi gned 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::Align Int(){
ok = 0;
}

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

void AlignInt::loadf ile(string filename){
if(ok) cout << "ERROR...me mory redesignation ERROR 1" << endl;
else{
filespec = filename;
ok = fileOKd(filespe c);
if(ok){
load_file();

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

// len_c....define d in load_file
// len_l....define d 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_cas t<char*>(ul);

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

void AlignInt::loads tring (string stringin){
if(ok) cout << "ERROR...me mory 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_cas t<char*>(ul);
for(unsigned int j = 0; j < len_c; ++j)
c[j] = stringin[j];

uc = reinterpret_cas t<unsigned char*>(ul);
ui = reinterpret_cas t<unsigned int*>(ul);
us = reinterpret_cas t<unsigned short*>(ul);
i = reinterpret_cas t<int*> (ul);
l = reinterpret_cas t<long int*> (ul);
s = reinterpret_cas t<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::preal igned(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_cas t<unsigned char*>(ul);
ui = reinterpret_cas t<unsigned int*>(ul);
us = reinterpret_cas t<unsigned short*>(ul);
i = reinterpret_cas t<int*> (ul);
l = reinterpret_cas t<long int*> (ul);
s = reinterpret_cas t<short int*> (ul);
c = reinterpret_cas t<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...me mory redesignation ERROR 3";
}

bool AlignInt::fileO Kd(string filespec){
ifstream in(filespec.c_s tr());
return in.good();
}
void AlignInt::verif y(){
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_cas t<unsigned int*>(uc) <<
"\n"
<< "p char " << reinterpret_cas t<int*>(c) << endl;
}
Jul 22 '05 #1
1 2075
"J. Campbell" <ma**********@y ahoo.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
7669
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 = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
6
2746
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 called "form1", and I have selects called "PORTA", "PORTB" ... etc...
38
5227
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 let's us do not go into an "each dot over i" clarification discussion now - however you want to call - you call it ;-) array contains records of all files in the current dir. array contains records of all subs in the current dir
18
4743
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 class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
0
12087
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 likelihood of CRM success from less than 20 percent to 60 percent. WHITEPAPER :
7
1622
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 a memory address is 32-Bit. Thus, if we have the following code: int i = 7; int* p = &i; Then memory is allocated to store a 32-Bit "int", and the value "7" is
5
575
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 system + OS e.g. Windows, Linux, WinCE. I am not quite sure about the alignment of the memory.... soln. 1: should be faster, I am not sure. idx size (bytes) 1 4
17
2324
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 same as its address. The second one simply depends on a term that is not well-defined. Most people consider the type to be an important part of the notion of
6
51164
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 help people display some nice widgets quickly without explaining some issues that need to be tackled when a full application needs to be developed. This article does not go into full implementation details because those can be found by reading the...
0
9455
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
9271
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
10031
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9838
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
9708
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6534
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();...
1
3805
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
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.