473,385 Members | 1,379 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,385 software developers and data experts.

dereferencing char array as int array

I'm a novice with c/c++ and have been reading Eckel's book. I'd like
some feedback on using this method. What I need to do is treat a
string as numeric data. I know how to write functions to convert
between data types, but was thinking that this isn't really necessary
since I can access the memory directly in c. I want to treat the text
as native integer so that I can perform fast bit-level manipulations.
This code works fine...but I'm wondering...is it portable? My main
concern is the byte order with the near byte being the leas
significant. I want to be *sure* that if I encode my text data as int
on one machine, that I can get my original text back on another. Will
this method work cross-platform? What are the dangers of doing this?
Is there an easier way? This is just sample code to demonstrate what
I am talking about...it's not meant to be useful. I appreciate any
input you can offer.

Joe

[code follows]
#include <string>
#include <iostream>

using namespace std;

int main(){
cout << "Enter some text" << endl;
string text;
getline(cin, text);

int tlen = text.length();
int extrabytes = tlen % sizeof(int);

cout << "Text has " << tlen << " characters. Must pad with "
<< sizeof(int) - extrabytes << " extra bytes for even "
<< "multiple of (int)" << endl;

tlen += sizeof(int) - extrabytes;

char chararray[tlen];
cout << endl << "CHAR ARRAY (index/value)" << endl;

for(int i = 0; i < tlen; i++){
if(i < text.length())
chararray[i] = text[i];
else chararray[i] = (char)0;

cout << i << " " << chararray[i] << endl;
}

cout << "String transfered to char array...and padded to fit"
<< " an int array\n"
<< "char array location " << &chararray << endl;

void* pa = chararray;
unsigned int* pa2 = ((unsigned int*)pa);

cout << "char array location will be dereferenced as"
<< " unsigned int..." << endl;

int arraylenint = tlen / sizeof(int);
unsigned int intarray[arraylenint];

cout << endl << "UNSIGNED INT ARRAY (index/value)" << endl;

for(int i = 0; i < arraylenint; i++){
intarray[i] = *pa2++;
cout << i << " " << intarray[i] << endl;
}

cout << "\n\nNote that each unsigned int (4-bytes on my machine)\n"
<< "takes the near byte as the least significant byte...\n"
<< "for example, if \"joec\" is entered, the output will be\n"
<< "1667592042...or \n"
<< "106*(256^0) + 111*(256^1) + 101*(256^2) + 99*(256^3)\n"
<< "where the ASCII values for j=106, o=111, e=101, c=99\n";

return 0;
}
[end code]
Jul 19 '05 #1
4 11947

"J. Campbell" <ma**********@yahoo.com> wrote in message
news:b9**************************@posting.google.c om...
I'm a novice with c/c++ and have been reading Eckel's book. I'd like
some feedback on using this method. What I need to do is treat a
string as numeric data. I know how to write functions to convert
between data types, but was thinking that this isn't really necessary
since I can access the memory directly in c. I want to treat the text
as native integer so that I can perform fast bit-level manipulations.
This code works fine...but I'm wondering...is it portable?
No
My main
concern is the byte order with the near byte being the leas
significant. I want to be *sure* that if I encode my text data as int
on one machine, that I can get my original text back on another. Will
this method work cross-platform?
No
What are the dangers of doing this?
Well as you say byte ordering. Although in theory a different computer could
use some radically different scheme of encoding integers, so the situation
might be even worse than a simple byte order change. In practice though I
would say that byte ordering is the issue you are likely to face.

Also of course integers needn't be the same size of different machines.
Is there an easier way?


To transfer integers between computers you mean? Use text, that's what its
for.

[snip]

john
Jul 19 '05 #2
This will definetely break between processors that are not little endian
The when converted ascii representation taken as ints the 4 bytes will
obviously follow the opposite format(BIg endian)
If this storage format is very much required, then first verify if processor
is little endian or big endian and then start processing the text. I guess
this would help to resolve machin independency.
ANy way, I feel the code u r trying out is only for understading the
language and not for any professional purposes,
Regards
vijay
Jul 19 '05 #3
Hello!

J. Campbell wrote:
I'm a novice with c/c++ and have been reading Eckel's book. I'd like
some feedback on using this method. What I need to do is treat a
string as numeric data. I know how to write functions to convert
between data types, but was thinking that this isn't really necessary
since I can access the memory directly in c. I want to treat the text
as native integer so that I can perform fast bit-level manipulations.
The char types are integer types. You don't need to do 'clever' things
with accessing the memory directly.
This code works fine...but I'm wondering...is it portable?
No...
My main
concern is the byte order with the near byte being the leas
significant.
That's one problem. How chars are encoded is another. Yet another is
how chars are stored in memory (they might be stored as just the low
eight bits of 32 bit words, with your char array being an array of 32
bit words, with only the low eight bits of each being used). Also,
related to encoding, there's the issue of how big the chars are (they're
not necessarily eight bits!).

Take Knuth's advice: premature optimisation is the root of all evil!
I want to be *sure* that if I encode my text data as int
on one machine, that I can get my original text back on another. Will
this method work cross-platform? What are the dangers of doing this?
Is there an easier way? This is just sample code to demonstrate what
I am talking about...it's not meant to be useful. I appreciate any
input you can offer.

Joe


Concentrate on getting the code *right*, first. Optimisation is hardly
ever relevant to correctness (and it is just a waste of time to optimise
incorrect code). Once you've got the code right (which, from what
you've said, means portable across platforms (and compilers)), *then*
optimisation *may* be appropriate.

However, optimisation isn't really something that novices should be
concerned with. For starters, knowing how to effectively optimise code
requires plenty of knowledge, understanding and experience. Secondly,
compilers perform all sorts of useful optimisations that just aren't
practical at the source code level (and such optimisation opportunities
can actually be pre-empted and prevented by naive, handwritten
'optimisations'). Thirdly, and most importantly, the best optimisations
aren't done at low, implementational levels (especially bit fiddly
stuff), but are done before any actual programming has even started -
they're done at higher levels in the design itself!

:-)

Simon

Jul 19 '05 #4
J. Campbell wrote:

To Simon G Best, re: "Take Knuth's advice: premature optimisation is
the root of all evil!"

I agree with what you are saying...however, I think that the more
details of a system that are understood, the greater liklihood for
writing efficient, well-formed code. Obviously I'm not there yet;-)

Thanks again for the response.


Given that, by your own admission, you're a novice: why do you think that?

Compare an unoptimised binary search (binary trees are lovely, lovely
things) of an ordered sequence of items with an optimised linear search
of the same sequence, and see how they compare for longer and longer
sequences. It will change your life.

(At the risk of sounding pretentious,) They who spend hours working for
a few more pennies can't spend that time earning lots of lovely pounds.

Simon

Jul 19 '05 #5

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

Similar topics

4
by: Pushkar Pradhan | last post by:
I have some functions which take as i/p a buffer (it can be float, char, or 16 bit, int etc.). The result is another o/p buffer, its type is also flexible (it could be a float, char etc.). I try...
5
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a...
12
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the...
28
by: Martin Jørgensen | last post by:
Hi, I have a "funny" question, which I think is pretty "healthy" to examine... This program is being investigated: - - - - - - - #include <iostream> using namespace std; #define DAYS 7
0
by: friend.05 | last post by:
I have three files. graph.h: My header file where I have typedef for my structure and function delcaration typedef struct _ipc_actors ipc_graph_actors; typedef ipc_graph_type...
4
by: Pritam | last post by:
line 7: error: dereferencing pointer to incomplete type 1. #include<stdio.h> 2. #include<sys/stat.h> 3. #include<stdlib.h> 4. void execname() { 5. struct task_struct *my; 6. my =...
3
by: David Mathog | last post by:
I have a program for which this line: if(! lstrtol(&atoken,length-2,(long *) &(lclparams->pad)) || (lclparams->pad< 0)){ generates the warning below, but ONLY if the gcc compiler is at -O2 or...
3
by: rasmidas | last post by:
Hi, I am having the following block of code. Should I use a NULL checking for tokens, where ever there is *tokens. Please let me know soon. while( !infile.eof() ) { ...
5
by: Anuz | last post by:
Hi all, While compiling a driver, I am getting this error: error: dereferencing pointer to incomplete type int __kc_adapter_clean(struct net_device *netdev, int *budget) { /*some...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.