473,671 Members | 2,193 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_bu f, &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 "deserializ e" these values is
safe and recommended:

x = htons(x);
memcpy(&buffer, &x, sizeof x);
/* Later, at the other end: */
x = ntohs(*((unsign ed 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 3736
Vlad Dogaru <dd****@gmail.c omwrites:
On May 2, 7:52 pm, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
> memcpy(&char_bu f, &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 "deserializ e" 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(*((unsign ed 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
11969
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 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...
11
55539
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--- #include "stdio.h" #include "string.h" void printText(char c){
2
32312
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 what order the data is stored so i try both ways. unsigned char array2 = { 0x23, 0x44, 0xc2, 0xde}; float *pfloat1, *pfloat2;
20
7083
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 string literal.
3
1983
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
2042
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 char array strarr holds garbage characters. For some reason, every time the strcpy function is called to copy the string in temp to the array, it fills the 0th element in the strarr array with garbage characters. Can someone try to compile this...
9
2375
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 somewhere within that array represent a counter. How can I take those 4 individual bytes, concatinate the 32bits that
9
7625
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 the function foo(). A pointer to char ** list is passed to foo() as an argument. The problem is that when foo() returns, char ** list contains rubbish
9
3123
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
10825
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
8390
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
8819
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
8596
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
7428
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
6222
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
5690
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
4221
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...
0
4399
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1801
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.