C++ casting

C

conf

long* long_pointer;

long_pointer is used to read 4 bytes each time.

Then,

short* short_pointer = [cast here]<short *>(long_pointer);

to read 2 bytes from now on.

Does this work?

What kind of C++ casting should use?

Thanks in advance!
 
G

Gianni Mariani

conf said:
long* long_pointer;

long_pointer is used to read 4 bytes each time.

Then,

short* short_pointer = [cast here]<short *>(long_pointer);

to read 2 bytes from now on.

Does this work?

What kind of C++ casting should use?

reinterpret
 
P

Phlip

conf said:
long* long_pointer;

long_pointer is used to read 4 bytes each time.

To read binary data, you must lie to the compiler. When you lie, the closer
to the truth the better. If you want shorts, declare an array of shorts:

short shorts[2];
whatever.read(shorts, 4); // something that reads bytes
 
J

JKop

conf posted:
long* long_pointer;

long_pointer is used to read 4 bytes each time.

Then,

short* short_pointer = [cast here]<short *>(long_pointer);

to read 2 bytes from now on.

Does this work?

What kind of C++ casting should use?

Thanks in advance!


A long isn't guaranteed to be 4 bytes.

A short isn't guaranteed to be 2 bytes.

A char *is* guaranteed to be 1 byte.


I'd suggest:


unsigned char *p_1byte;

unsigned char (*p_2bytes)[2];

unsigned char (*p_3bytes)[3];

unsigned char (*p_4bytes)[4];

unsigned char (*p_5bytes)[5];

unsigned char (*p_6bytes)[6];


That said though, a "char" isn't guaranteed to be 8 bits. According to the
Standard, a byte isn't guaranteed to be 8 bits.

Definitions of a "byte":

Domestic) 8 bits

C++ Standard) The smallest unit of accesable/allocatable memory on a
machine


A char is one C++ Standard byte. The Standard does guarantee however that a
byte is atleast 8 bits.


-JKop
 
B

Bob Hairgrove

long* long_pointer;

long_pointer is used to read 4 bytes each time.

....unless you are running on a 64-bit machine, in which case the
pointer will most likely occupy a different number of bytes (but ...
you shouldn't care about bytes, just the ponter's type).
Then,

short* short_pointer = [cast here]<short *>(long_pointer);

to read 2 bytes from now on.

Does this work?

You can (should) use reinterpret_cast<short*>(long_pointer) in order
to access short values through the pointer (which might or might not
be 2 bytes long).
What kind of C++ casting should use?

reinterpret_cast, as given above. But forget about bytes ... if you
really need bytes, cast to unsigned char* and do binary reads and
writes.

(I hope this clarifies the information given in the other responses a
bit.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top