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

Home Posts Topics Members FAQ

Casting a byte array to allow assignment

I found the following code floating around somewhere and I'd like to
get some comments.

unsigned char a1[4]= { 5,10,15,20};
unsigned char a2[4]= { 25,30,35,40};

*(unsigned int *)a1=*(unsigned int *)a2;

// now a1[0]=a2[0], a1[1]=a2[1], etc.

This is taking a byte array, casting it to a 4 byte integer pointer,
then dereferencing it, then assigning it. This results in the contents
of array a1 copied to array a2. (corrections to my interpretation
welcome)

I don't know why this was done this way. My first instinct would have
been to use memcpy. Is this faster than memcpy? Are there any dangers
other than the potential for int not being 4 bytes?

Jul 24 '06
20 3512

Keith Thompson wrote:
en******@yahoo. com writes:
Dave Thompson wrote:
On Mon, 31 Jul 2006 07:31:53 GMT, Keith Thompson <ks***@mib.or g>
wrote:
Dave Thompson <da************ *@worldnet.att. netwrites:
To be pedantic, alignof (unsigned char [4]) % alignof (unsigned int)
== 0. Although it is clearly expected and normally true that stricter
alignments (if they exist at all) are multiples of all looser ones,
that isn't explicitly required; a perverse (DS9k) implementation could
align char[4] to 3 and int to 5.
[...]

Actually, I don't think it could. int could have an alignment of 5,
but char[4] can't have a required alignment of 3. Given:

char arr[2][4]

the two elements of arr must be adjacent and must each have a size of
4 bytes.

Oops, you're right. I didn't think far enough.

In general, because there can't be gaps between array elements, the
size of a type must be a multiple of its alignment. (The
implementation can adjust the size if necessary to make this happen,
for example by adding padding bits.)

Except to character types, or at least unsigned char and thus possibly
plain char. And, by the reasoning above, arrays of them.

But I still maintain in the example upthread int could (perversely)
require an alignment not supplied by char[4].
Are you saying anything more than, eg, char[4] can
require four byte alignment whereas int could allow
alignment of either 0 or 2 mod 4? Certainly the
set of alignments allowed for int must have some
overlap with the set of alignments allowed for
char[4].

int could have an alignment of, say, 5. If char[4] required an
alignment of 4, then a union of an int and a char[4] would require an
alignment of at least 20.
My assumption was the earlier context stipulated an
int of size 4. If int were of size 5 then I agree
with your comment. Also note, my comment was only
an example.
But I'm not sure that char[4] can require an alignment stricter than 1
byte. For example, this:

char buf[5];
char (*p)[4] = (char(*)[4])(buf+1);

make p a pointer to a char[4] array that aliases elements 1..4 of buf.
Is this guaranteed to make p a valid pointer?
I believe the Standard does not guarantee p will be valid,
either directly or indirectly. And, to draw the conclusion,
the guarantee of validity would need to be explicit.
More generally, may an array of type X have a stricter alignment
requirement than type X itself?
Yes, I believe it may, provided the array has a defined
array bound that is greater than one.
An implementation may, of course, choose to align a char array, or
even a single char object, on, say, a word boundary; the question is
whether it can require such strict alignment.
Yes; unless there is specific language that shows
such an alignment can't be required, it can be
required. I'm not aware of any such language for
arrays of length greater than one.

Aug 15 '06 #21

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

Similar topics

4
19275
by: David Rager | last post by:
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!
20
2109
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
7
3676
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
3
54258
by: glenn | last post by:
I have a COM server that is returning a type Object that I need to cast as a byte array. Can anyone tell me how this is performed in C#? Thanks, glenn
3
2132
by: Dennis | last post by:
If I have a byte how would I port code from C++ to manipulate the byte array as if it were a long? For example: // C++ // assume the following // unsigned char* m_pPalette; // unsigned char* m_pData; //
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...
12
3325
by: O.B. | last post by:
I'm trying to do a static_cast at runtime in C# and as I understand it, "as" is the keyword to use. Unfortunately, the compiler is trying to do the cast a compilation time. See below. /* TestA.cs */ namespace TEST { class TestA { public ushort val1; public ushort val2; public ushort val3;
57
3238
by: buuuuuum | last post by:
why array can't be assigned, like structs?
11
7287
by: jois.de.vivre | last post by:
I am interfacing with a third party API (written in C, if that matters) that has an "event handler" function with the following definition: void event_handler(int event_code, unsigned long user_data); The function takes an event code along with the user data but does not act on or change the user data. In my application, I want to pass a pointer as the user data. This pointer is to an array allocated with new, say, as follows:
0
9178
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
9035
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
8916
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
7752
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
5875
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();...
0
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3058
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
2348
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2010
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.