473,667 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy 4 byte block into a char array

Hi,

I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?

Thanks,

Barry.

Jun 21 '06 #1
10 9387
b...@yahoo.com wrote:
ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


Write a function or macro.

It's called "modular design" where instead of copy/pasting the same
code snippet you found on snippets.org you actually build up a program
from a design where you abstract out common functionality to a body,
almost a "library" if you will, of support code for your application or
project.

Tom

Jun 21 '06 #2
bg***@yahoo.com writes:
Hi,

I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


You could probably try this:

memcpy(&arr[12],&tmp,sizeof(in t));

Just make sure you know exactly what you're doing. For example int
doesn't need to be 4 byte long.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Jun 21 '06 #3
<bg***@yahoo.co m> wrote in message
news:11******** **************@ g10g2000cwb.goo glegroups.com.. .
I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


You can't, portably.

1. The endianness of a particular machine may cause the bytes to be assigned
to different chars than what you've listed above.
2. element[12] may not have proper alignment for an int, causing a crash.
3. sizeof(int) may not be 4, causing more than 4 elements of your array to
be modified.

This is why folks write macros (which assign the bytes in a specific order)
for such needs.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
--
Posted via a free Usenet account from http://www.teranews.com

Jun 21 '06 #4
On Wed, 21 Jun 2006 13:17:46 -0700, bg_ie wrote:
int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


if you know that you're on a big-endian machine and sizeof char * 4 ==
sizeof int, you could theoretically do:

int *slice;
slice = &arr[12];
*slice = tmp;

but that's obviously unportable as hell

Jun 21 '06 #5
Stephen Sprunk wrote:
How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


You can't, portably.


....sorta.

In my projects I try to autodetect certain platforms and use memcpy if
possible, otherwise yeah I extract bytes and store in order.

Tom

Jun 21 '06 #6
bg***@yahoo.com writes:
I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


int isn't necessarily 4 bytes, bytes aren't necessarily 8 bits, and
the value 0x01020304 isn't necessarily stored in the order 1, 2, 3, 4;
it's commonly 4, 3, 2, 1, but it could theoretically be in any of the
24 possible orders.

If you want to break the value of tmp down into 4 8-bit quantities,
and store then in successive elements of your array (it it called
"arr" or "ThePacket3 "?), the only portable way to do it is by copying
each byte individually, after extracting them using shifts and masks.

If you're willing to make non-portable assumptions about how an int is
represented, you can use memcpy(), but your code will break when
ported to a system with different byte ordering.

If you're trying to guarantee network byte ordering, there are
functions that will handle this for you ("ntohl" and friends), but
they're not part of standard C. If your system has them, searching
your documentation for "ntohl" should be enough to get you started.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 21 '06 #7
On 21 Jun 2006 21:00:19 +0000, Nelu <sp*******@gmai l.com> wrote:
bg***@yahoo.co m writes:
Hi,

I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


You could probably try this:

memcpy(&arr[12],&tmp,sizeof(in t));

Just make sure you know exactly what you're doing. For example int
doesn't need to be 4 byte long.


And make sure that an int on the system is big-endian otherwise the
result will not be as specified.
Remove del for email
Jun 22 '06 #8
On Wed, 21 Jun 2006 16:26:03 -0500, James <ho**********@h otmail.com>
wrote:
On Wed, 21 Jun 2006 13:17:46 -0700, bg_ie wrote:
int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?

if you know that you're on a big-endian machine and sizeof char * 4 ==
sizeof int, you could theoretically do:

int *slice;
slice = &arr[12];
*slice = tmp;


You need a cast on the pointer assignment and the code will invoke
undefined behavior if arr[12] is not properly aligned for an int.

but that's obviously unportable as hell

Remove del for email
Jun 22 '06 #9
bg***@yahoo.com wrote:

I have an array as follows -

char arr[100];

Now I wish to copy the following int -

int tmp = 0x01020304;

into this array, at element[12].

This following would have the same result -

ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;

How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?


Assuming your specs are accurate, and you change the type of tmp to
unsigned long, you can do it independant of endianism etc. by using
values, not bit patterns:

unsigned char ThePacket[100];
unsigned long tmp;
int i;

for (i = 3; i >= 0; i--, tmp /= 256)
ThePacket[12 + i] = tmp % 256;

You should be using unsigned items for both tmp and ThePacket. tmp
must be a long to guarantee 32 bits available.

If it can the compiler will probably optimize the modulo and
division operations into shifts and masks. Writing portable code
isn't all that hard, is it?

Notice that the values 3 and 12 above can be defined as FIELDSZ and
FIELDLOCN, or whatever nomenclature suits you.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 22 '06 #10

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

Similar topics

9
42776
by: Thomas J. Clancy | last post by:
I was wondering if anyone knew of a way to use std::copy() and istream_iterator<>/ostream_iterator<> write a file copy function that is quick and efficient. Doing this messes up the file because it seems to ignore '\n' ifstream in("somefile"); ofstream out("someOtherFile"); std::copy(std::istream_iterator<unsigned char>(in),
11
461
by: Peter | last post by:
Hi how can I compare two byte arrays in VB.NET Thank Peter
4
8807
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where a * occurs in the string). This split function should allocate a 2D array of chars and put the split results in different rows. The listing below shows how I started to work on this. To keep the program simple and help focus the program the...
15
34583
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
8
10707
by: intrepid_dw | last post by:
Hello, all. I've created a C# dll that contains, among other things, two functions dealing with byte arrays. The first is a function that returns a byte array, and the other is intended to receive a byte array as one of its parameters. The project is marked for COM interop, and that all proceeds normally. When I reference the type library in the VB6 project, and write the code to call the function that returns the byte array, it works
15
435
by: Kueishiong Tu | last post by:
How do I copy the content of a string in one encoding (in my case big5) to a char array (unmanaged) of the same encoding? I try the following String line = S"123æ°´æ³¥"; char buffer; for(int i=0; i<line->get_length(); i++) {
3
12791
by: marfi95 | last post by:
Hi all. I need to copy a byte array into a string, but starting at a specific location in the byte array. This is where I get hung up. For example if my byte array is (100) big, I might want to start at position 60 for example and copy from 60 to the next null byte in the array to my string. The starting position is variable, as is where the next null byte is in the byte array. The array I'm dealing with is much bigger than that, so...
8
1758
by: mast2as | last post by:
I almost apologize to ask this question but I have been starting at this code for a bit of time and don't understand what's wrong with it. I am not arguing about the fact it's good or not coding, it's actually a shorter version of something more complex that i am doing. Anway the idea is that there's a func Test which takes a pointer to void argument, allocate some memory, set this memory with some cotent, assign the ptr to a void to the...
2
5030
by: =?Utf-8?B?QmFydE1hbg==?= | last post by:
Greetings, I am trying to copy an unmanaged buffer into a mananged buffer, and trying to use marshalling, and I am not having any success because it doesn't seem to complie. Basically I am using Directshow's sample grabber interface to a filter, and trying to copy a buffer to a managed buffer will little success. I get an error that my paramaters do match. I change the parameters, and still can't seem to get the marshall to compile. ...
0
8457
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
8365
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,...
1
8563
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
8646
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
7390
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...
1
6203
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5675
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
4200
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...
2
2013
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.