473,698 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

memcpy a int to a char buffer ?

Hello,
i want to do store int variablen into a char Buffer.
Like this:

char Buffer[1024];
int b = 1447;
int *pb; // pb deklariert als pointer auf int
pb = &b; // & ist Adress operator, liefert Adresse von b
memcpy( Buffer, pb, 4 );

This seem to work but now i want to copy the int Variable to another
position in the buffer. How do i this ?
This causes a error:

char Buffer[1024];
int b = 1447;
int *pb; // pb deklariert als pointer auf int
pb = &b; // & ist Adress operator, liefert Adresse von b
memcpy( Buffer[100], pb, 4 ); // cause: error C2664: 'memcpy' : cannot
convert parameter 1 from 'char' to 'void *'

How can i do this ?
Jan 23 '06 #1
6 36560

"Juergen Wohnich" <Ju*********@gm x.de> wrote in message
news:dr******** **@online.de...
Hello,
i want to do store int variablen into a char Buffer.
Like this:

char Buffer[1024];
int b = 1447;
int *pb; // pb deklariert als pointer auf int
pb = &b; // & ist Adress operator, liefert Adresse von b
memcpy( Buffer, pb, 4 );

This seem to work but now i want to copy the int Variable to another
position in the buffer. How do i this ?
This causes a error:

char Buffer[1024];
int b = 1447;
int *pb; // pb deklariert als pointer auf int
pb = &b; // & ist Adress operator, liefert Adresse von b
memcpy( Buffer[100], pb, 4 ); // cause: error C2664: 'memcpy' : cannot
convert parameter 1 from 'char' to 'void *'

How can i do this ?


To answer the error you are getting, Buffer[100] is the char at position
101. You just want the address of this or
&Buffer[100].
Jan 23 '06 #2
you can do some casting to get the same result

*(reinterpret_c ast<int*>(&Buff er[the_position_yo u_want_to_start])) = n;

Some comments:
- get char pointer with &Buffer[the_position_yo u_want]
- cast this point to int pointer with reinterpret_cas t<int*>(...)
- set the value at that pointers address with *(...) = b

--

Henryk

Jan 23 '06 #3
"Henryk" <he************ @gmx.de> wrote in news:1138041999 .340362.153120
@g49g2000cwa.go oglegroups.com:
you can do some casting to get the same result

*(reinterpret_c ast<int*>(&Buff er[the_position_yo u_want_to_start])) = n;

Some comments:
- get char pointer with &Buffer[the_position_yo u_want]
- cast this point to int pointer with reinterpret_cas t<int*>(...)
- set the value at that pointers address with *(...) = b


Oh no you can't.... (not according to the Standard anyway). Try it on the
Sparc platform for example. If the_position_yo u_want doesn't result in a
correctly aligned memory access for deferencing that pointer... your
program will crash (one possible result for the Undefined Behaviour that
was invoked).
Jan 23 '06 #4
Ok, that is new to me.

We have Sparc Leons inhouse. But it is too long ago that I worked with
to remember...

Just for my interest:

Could you give some more explanation why it would crash? Must an
integer value 2- or 4-byte aligned in memory? What about derefencing
the pointer back to char? Are there any alignment constraints then?
What about 1-byte packed structures?

Jan 24 '06 #5
"Henryk" <he************ @gmx.de> wrote in news:1138106524 .148895.293440
@g49g2000cwa.go oglegroups.com:
Ok, that is new to me.

We have Sparc Leons inhouse. But it is too long ago that I worked with
to remember...

Just for my interest:

Could you give some more explanation why it would crash? Must an
integer value 2- or 4-byte aligned in memory? What about derefencing
the pointer back to char? Are there any alignment constraints then?
What about 1-byte packed structures?


As I recall, due to the instruction set on the processor, it can't
load/store an int-sized chunk of memory into a register from an unaligned
memory address.

So, with the example:

char buffer[1024];

*(reinterpret_c ast<int *>(&buffer[1])) = 2;

The compiler may emit the machine code to load 2 into a register, then
attempts to store the register into the memory address &buffer[1]. The
hardware doesn't allow it, so the CPU generates a trap. This ends up
manifesting itself as a bus error in your program, and your program
crashes.

Accessing an int inside a 1-byte packed structure isn't an issue since
the compiler can examine your int access and realize that since it is
accessing the int from an unaligned address it will emit the machine code
to do the extra memory accesses (in order to comply with the aligned
memory access rules) to compose the int. So if you had (assuming
whatever compiler magic to make it 1-byte aligned):

struct st
{
char ch;
int anInt;
};

st stVar;
char * overlay = reinterpret_cas t<st *>(&stVar);

In the example above it reads the 4 bytes starting at &overlay[0] into a
register, left shifts it 8 to throw away the 1st byte, then load the byte
at &overlay[4] and bitwise-or it with the working register to finally get
the complete int. Note that &stVar is by definition correctly aligned
for an object of type st.

To bring this discussion back to the Standard realm (from Sparc-
specific), the original code has undefined behaviour because you're
casting a pointer between unrelated types (and not void*).

What does work:

char buffer[1024];
int someInt(2);

memcpy(&buffer[1], &someInt, sizeof(someInt) );

memcpy has to be able to deal with unaligned memory copies, so this would
work. (Exactly how it works is the problem of the compiler implementor,
as well as any sort of optimizations)
Jan 24 '06 #6
Ok, thank you. Got your point.

About the undefined behavior:

I thought the purpose of reinterpret_cas t is to tell the compiler "shut
up I know what I do", which is true sometimes...

I do this cast pretty often. For instance to extract data from a byte
stream. Suppose the byte stream contains a float value somewhere
(possibly bytes had to be swapped before fron sender/receiver because
of endian mismatch). This cast is the most efficient way to extract the
data.

The overhead of memcpy for only a few bytes (8 for float) is just too
much.

It worked so far but good to know the pifalls at some machines as you
pointed it out.

Greets

--

Henryk

Jan 24 '06 #7

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

Similar topics

2
2522
by: Steffen Conrad | last post by:
Hi, I want to buffer a large amount of ASCII-output (some 100 MB). Therefore I'm asking myself, if when using a stringstream for this would cause a mentionable loss of performance against a dynamically allocated char-buffer. Bye, Steffen
1
2634
by: Alex Vinokur | last post by:
I have several questins concerning a program below. ------ foo.cpp : BEGIN ------ #include <cassert> #include <cstdlib> #include <iostream> #include <fstream> using namespace std; int main()
2
3016
by: derek.google | last post by:
I have an application that's crashing because of an alignment problem, and this is the smallest program that demonstrates what's happening: int main() { struct Message { unsigned short size; }; const int START_INDEX = 1; char* buffer = new char; Message* msg = (Message*)&buffer;
5
17637
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
1
2212
by: Sergey Muschin | last post by:
Hi there, i need to send a socket message to TCP socket server. Server has been implemented with VC 6.0 and expects from client the message in this format typedef struct { int msg_nbr; // Message number from list below // Profile data int iPar1;
2
2341
by: On the Sparrow | last post by:
I have a 3rd party API that store compressed JPEG data in a char buffer.ll How do I convert it to either an System::Drawing or somekind of format that I can display in a Windows::Form?
6
4674
by: vaidehikedlaya | last post by:
Hello, I am using gmp.h library. I am trying to put mpz_t variable into char buffer and back. I came across mpz_import/mpz_export to suffice this purpose. But, I am not very clear about using these functions. I am not getting the right result for the program below. In the program I have included the code(present in the gmp document, in the description of mpz_export function) numb = 8*size - nail;
4
2134
by: cmare | last post by:
Hello, I don't know not much about C++, so here I have an example of code, and I don't now how to call it :( It should return an string from console to microcontroler. BYTE ConsoleGetString(char *buffer, BYTE bufferLen) { BYTE v; BYTE count; count = 0;
2
4154
by: Rasheed | last post by:
Hi, i have a char pointer buffer which will hold the bitmap buffer, So i need to convert char *buffer as a bitmap. becuase when i draw on the Dialog using char *buffer. Nothing will be dispalyed. So kindly can any body help me how to convert char *buffer to bitmap. i want the solution in C++
0
8683
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
9170
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
9031
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...
0
8871
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
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.