473,386 Members | 1,609 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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 36497

"Juergen Wohnich" <Ju*********@gmx.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_cast<int*>(&Buffer[the_position_you_want_to_start])) = n;

Some comments:
- get char pointer with &Buffer[the_position_you_want]
- cast this point to int pointer with reinterpret_cast<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.googlegroups.com:
you can do some casting to get the same result

*(reinterpret_cast<int*>(&Buffer[the_position_you_want_to_start])) = n;

Some comments:
- get char pointer with &Buffer[the_position_you_want]
- cast this point to int pointer with reinterpret_cast<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_you_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.googlegroups.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_cast<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_cast<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_cast 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
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...
1
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...
2
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;...
5
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...
1
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; ...
2
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
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...
4
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...
2
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....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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...

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.