473,699 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting Arrays

Howdy,

Put briefly, I have an array of chars, which I would like to access in pairs
of bytes via casting the array to an array of shorts. I'm trying to be as
elegant as possible.

Below is a program with a failed attempt. Hopefully it will help clarify the
issue :).

Thanks!
David

#include <iostream>
int main() {
char cbuff[32];
short * sbuff = (* short) &cbuff; // my failed attempt
sbuff[10] = 65;
cout << cbuff[21] ; // should output A
}
Jul 22 '05 #1
4 19274

"David Rager" <ra*****@nospam memail.utexas.e du> wrote in message
news:bp******** **@geraldo.cc.u texas.edu...
Howdy,

Put briefly, I have an array of chars, which I would like to access in pairs of bytes via casting the array to an array of shorts. I'm trying to be as
elegant as possible.

Below is a program with a failed attempt. Hopefully it will help clarify the issue :).

Thanks!
David

#include <iostream>
int main() {
char cbuff[32];
short * sbuff = (* short) &cbuff; // my failed attempt
sbuff[10] = 65;
cout << cbuff[21] ; // should output A
}


In your cast, you need (short *) rather than (* short).

You'll also need std::cout instead of cout since you didn't "using namespacr
std;"...
Jul 22 '05 #2
Thanks - cleared it right up! :)
Jul 22 '05 #3
> Put briefly, I have an array of chars, which I would like to access in
pairs
of bytes via casting the array to an array of shorts. I'm trying to be as
elegant as possible.


I must confess I have trouble understanding a context in which this kind of
type cheating can be considered elegant.

What problem are you trying to solve?
Jul 22 '05 #4
"David Rager" <ra*****@nospam memail.utexas.e du> wrote in message news:<bp******* ***@geraldo.cc. utexas.edu>...
Howdy,

Put briefly, I have an array of chars, which I would like to access in pairs
of bytes via casting the array to an array of shorts. I'm trying to be as
elegant as possible.


Hi David,

Let me preface by saying that I'm not all that experienced with c++,
and so there may be other issues with what I'm about to write.

I had the need to do similar casting recently...I was accessing a char
array as an array of unsigned long ints. Someone raised the issue of
"alignment" , which could present portability problems. The issue is
basically this. Suppose you have an array of 10 ints, a[10], and you
want to access the 2nd & 3rd bytes as a short (ie a[1] & a[2]). It is
possible that short can only be aligned with bytes that are an
even-multiple offset from the start of the memory space. That is,
your short int pointer can only point to(in char*) a[0], a[2], a[4],
a[6], a[8] indexed as ashort[0] - ashort[4].

What I ended up doing was to turn the problem around. I made a class,
AlignInt, that creates an empty int (or short) array, loads the
char-data into that array, and then give the user pointers to that
data as signed or unsigned char, short, int, and long. So...for
example, if I had the char string "abcdefgh" and I wanted to access
short int words from the same memory location as "bc", "de", "fg",
"hNULL", (note this case doesn't use the first byte...this is the sort
of case that could cause alignment issues). I first create an empty
4-word array of short, cast the array to char*, load the substring
"bcdefgh" into the array, then safely access as either data-type.

Anyway...just food for thought. If you want to see or use this class,
just ask. It accepts string, a file, or an existing aligned array,
and gives public access to the data and array length represented as
any of the native data-types.
Jul 22 '05 #5

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

Similar topics

2
2490
by: ghostdog | last post by:
hi, i got this opengl/c++ code: <code> void render(CMesh *mesh){ ... float *pVertices; int *pIndices;
4
1493
by: Stewart Stevens | last post by:
I have a structure that looks like this: public __value struct mytype { float first; float second; }; I am trying to pass arrays of these things over a socket. So I have:
4
1931
by: John Ratliff | last post by:
Say I had a three-dimensional array containing multiple 2D level data. It might be defined like this: unsigned char LEVEL_DATA = { { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1},
4
4504
by: kelli | last post by:
i am new to c# so if this is a trivial problem, forgive me! i've searched the web and after 2 days still cannot solve it. i am converting a c++ application to c# - the problem code is listed below. the c++ code uses a byte array (msg) to hold a serial message. since the message can be of different layouts, the array is cast to the appropriate layout "type" (struct SERIAL_CAN_MSG_TYPE, in this example). to complicate things, there is an...
61
4565
by: Ken Allen | last post by:
I am relatively new to .Net, but have been using VB and C/C++ for years. One of the drawbacks with VB6 and earlier was the difficulty in casting a 'record' to a different 'shape' so one could perform different manipulations on it. For example, I have a complex data structure, which I can represent in a VB6 TYPE declaration, but I cannot easily convert that to a fixed length array of unsigned bytes so that I could perform a checksum...
2
2165
by: Enrique Bustamante | last post by:
Casting arrays that works on watch and command window but not in code. My application is casting arrays in a way it should work. To test if I was doing something invalid, I wrote a test code that has similar structure of the classes in my application. The test worked fine, the casting I want to do must work. I compared the structure of the test with the application to ensure they where similar (inheriting twice, base class implements...
5
3873
by: Diffident | last post by:
Hello All, I have a 2-dimensional array that I am storing as a session variable. I have no idea on how I can cast the session variable back to 2-dimensional array. Any pointers? Reference code below... Array declaration: DateTime DateRangesForDataLists = new DateTime;
2
8740
by: stunt016 | last post by:
I have a program written in C# that handles communication between two pieces of software. My problem only deals with getting a text array from one program to this C# "Bridge". I can get the text array to the bridge, where it is received as a system.object. My problem is casting this system.object to a string array. The code I'm using is below. System.Array advArgs = args as System.Array; //creates array for parameters being...
13
4954
by: Boon | last post by:
Hello everyone, Consider a "set" of M=N*N integers. In some parts of my program, I want to handle this set as a 1D array of M integers. In other parts of my program, I want to handle this set as a 2D matrix of N*N integers. Is the following code 100% legal C89 code ? #include <assert.h> #define N 9
0
8686
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
8615
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
9173
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...
0
9033
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
8911
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
7748
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
5872
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();...
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
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.