473,511 Members | 9,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Putting an int value in a char array

On May 2, 7:52 pm, Ben Bacarisse <ben.use...@bsb.me.ukwrote:
memcpy(&char_buf, &int_var, sizeof int_var);
[snip]
The shifting method (used on unsigned types) can give you
a portable solution.
Would memcpy and htons & co be a correct approach? My problem is that
it's not only short ints that I have to accomodate, but also the
occasional long; I'd like to have a uniform handling of these
operations.

Also, I'm not sure if the way I found to "deserialize" these values is
safe and recommended:

x = htons(x);
memcpy(&buffer, &x, sizeof x);
/* Later, at the other end: */
x = ntohs(*((unsigned short *) buffer));

I only need unsigned values, so unsigned {short, long} should be
enough. And one final question: would there be any reason to using
uint16_t and uint32_t instead of unsigned short and unsigned long?

Thanks and sorry for the question avalanche,
Vlad
Jun 27 '08 #1
2 3722
Vlad Dogaru <dd****@gmail.comwrites:
On May 2, 7:52 pm, Ben Bacarisse <ben.use...@bsb.me.ukwrote:
> memcpy(&char_buf, &int_var, sizeof int_var);
[snip]
The shifting method (used on unsigned types) can give you
a portable solution.

Would memcpy and htons & co be a correct approach?
First htons and htnol (the "long" version) are POSIX, so technically
off topic here. They are an excellent choice for this problem but
they incur a cost that can be avoided if you are designing a system
for CPUs where the "host" representation is different to the "network"
one. If you can use you own functions, you can avoid this (probably
small) cost by making these operations "null" on your main platform.
My problem is that
it's not only short ints that I have to accomodate, but also the
occasional long; I'd like to have a uniform handling of these
operations.
Then there is htonl and ntohl that take uint32_t values. Note that C
does not insist that long is 32 bits, but uint32_t is.
Also, I'm not sure if the way I found to "deserialize" these values is
safe and recommended:

x = htons(x);
memcpy(&buffer, &x, sizeof x);
That is the safe, portable, way. However, a lot of code will be able
to define the buffer as struct with integer members, so one often
sees:

msg.data1 = htons(x);

or even, the more dangerous:

*(uint16_t *)buffer = htons(x);

The memcpy version avoids any alignment problems and so it more portable.
/* Later, at the other end: */
x = ntohs(*((unsigned short *) buffer));
The reverse would have been

memcpy(&x, &buffer, sizeof x);
x = htons(x);

but the dangerous cast is often used. Data formats in protocols are
often chosen so that there will be no alignment problems on most
common processors, so you will have to decide between portability,
code clarity and speed of packing knowing what you know about the
target systems and the purpose of the code.
I only need unsigned values, so unsigned {short, long} should be
enough. And one final question: would there be any reason to using
uint16_t and uint32_t instead of unsigned short and unsigned long?
Yes. The most important is that POSIX now defines the [nh]to[hn][ls]
functions in terms of these types. These days, you are more likely
to find a system where short 16 bits or long 32 bits than you are
to find one where uint32_t is either not defined or is hard to define
yourself.

--
Ben.
Jun 27 '08 #2
On May 3, 5:01 pm, Ben Bacarisse <ben.use...@bsb.me.ukwrote:
Yes. The most important is that POSIX now defines the [nh]to[hn][ls]
functions in terms of these types. These days, you are more likely
to find a system where short 16 bits or long 32 bits than you are
to find one where uint32_t is either not defined or is hard to define
yourself.
Thank you for all your time, Ben.

Vlad
Jun 27 '08 #3

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

Similar topics

4
11957
by: J. Campbell | last post by:
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...
11
55478
by: Pontus F | last post by:
Hi I am learning C++ and I'm still trying to get a grip of pointers and other C/C++ concepts. I would appreciate if somebody could explain what's wrong with this code: ---begin code block--- ...
2
32273
by: Goran | last post by:
Hi! I need to convert from a unsigned char array to a float. I don't think i get the right results in the program below. unsigned char array1 = { 0xde, 0xc2, 0x44, 0x23}; //I'm not sure in...
20
7058
by: Petter Reinholdtsen | last post by:
Is the code fragment 'char a = ("a");' valid ANSI C? The problematic part is '("a")'. I am sure 'char a = "a";' is valid ANSI C, but I am more unsure if it is allowed to place () around the...
3
1961
by: s.subbarayan | last post by:
Dear all, I encountered the following piece of program: #include <stdio.h> void strprint(char *str); void main() { char *spr="hello"; strprint(spr); }
2
2033
by: Amrit Kohli | last post by:
Hello. I have the following code, to do a simple operation by copying the elements of a vector of strings into an array of char pointers. However, when I run this code, the first element in the...
9
2367
by: Noel Milton | last post by:
Hi: Ok, I've just read in up to 65,535 bytes into a char array (using the recvfrom socket API call). So I have an array of 8 bit char's (char recvString;). Now, four (4) consecutive bytes...
9
7609
by: rob.kirkpatrick | last post by:
Hello I need to populate an array of char arrays at run-time. A very simplifed version of the code is below. char ** list should contain cnt char arrays. The values of char ** list are set by...
9
3118
by: Angus | last post by:
Hello I want to write a function which returns a char array. But if I write this: char myfunction() { return "123"; }
8
10814
by: Tricky | last post by:
Is there a way I can easily convert a char array into an int array, without having to cast each value in the array to an int and copying it to a new array? Thanks for any help :)
0
7251
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,...
0
7367
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,...
0
7430
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...
1
7089
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...
0
7517
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...
0
4743
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...
0
3217
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
790
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
451
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...

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.