Yeah, it should be buffer[0-3]. On my architecture int is four bytes.
Specifically what I was trying to do is to take a long segment of byte
data and periodically write header information to it so that I can
split it up to be processed on a parallel architecture. The header info
Is the splitter part of the architecture, or a separate front-end or
manager or whatever? In particular, do you KNOW they are the same
endian (as well as the same size = 4 bytes and the same bytesize,
and no differences in padding -- or just no padding at all)?
(the four byte ints) point to the beginning of sub-sections so that
they can be processed as a cohesive unit.
for instance, I want my byte stream to appear as thus:
10aaaaaa6bb8cccc
where the numbers are four byte ints and the letters are arbitrary one
byte symbols. The integers point to the beginning of the next
segment, denoting the length of a subsection. The 10 indicates that
the first subsection is 10 bytes in length and the subsection begins
IAYM the _next_ subsection, really the next count, begins at 10.
at buffer[10]. In actuality these subsections are going to be much
longer, which is the reason I need a greater number of bits than a
single byte.
This brings up the already-mentioned issue of alignment. If this
buffer is (at the beginning of) malloc'ed space, it is correctly
aligned for any C datatype -- including int. But buff+10 bytes is NOT
guaranteed to be aligned correctly, and for some systems it isn't.
If your system doesn't have alignment requirements, you're OK.
If it has only a 'soft' requirement (misaligned access still works but
is slower) and the amount of accesses to these count fields is small
(enough) compared to your other processing, still OK. Otherwise, you
have two choices:
- do the byte-by-byte access, either explicitly or with memcpy. This
will probably be a little slower on every count, although compared to
the rest of your processing it is likely negligible.
- move each count position to the next aligned location, wasting up to
3 bytes (padding) as needed. If the data is already large, as you say,
wasting say .0001% or whatever of the buffer space may be OK.
Best regards to everyone and thanks for the illuminating responses. I
actually didn't realize that you could cast a memory buffer to change
the indexing. I knew bit shifting would probably work, but I always
manage to screw things up and introduce bugs, plus I save cycles by
casting because it is done at compile time, right?
Not necessarily. But most machines nowadays are byte addressed, so
(data) pointer conversions require no actual computation, they only
change the type of the value. On the rare machines where say an int
pointer is different, and you want to do an int access, then the
runtime conversion is needed and had better be done.