Sign in to follow this  
beebs1

STL Iterator Casting

Recommended Posts

Hiya,

If anyone could help with this it would be appreciated.

I have an STL vector of chars, and an iterator pointing at a certain position. I need to cast the 4 bytes which are 8 bytes ahead of the iterator into an int, so I can assign to it - but I'm not sure of the syntax.

[code]
/* If it was a regular array, I could do: */
unsigned char buffer[500];
int index = some_value;
*(unsigned int*)&buffer[index + 8] = value;

/* I'm not sure of the syntax when using STL & iterators. */
std::vector<unsigned char> buffer;
std::vector<unsigned char>::iterator itr = buffer.begin();
*(unsigned int*)(*itr + 8) = value; /* I believe this adds eight to the value of the char, but something similar? */
[/code]

It's actually for a stream cipher - I'm not just being obtuse :)

Thanks very much for any suggestions.

Share this post


Link to post
Share on other sites
I think the result is undefined due to potential alignment issues.

Original C code breaks just about every guarantee C++ and STL try to make. If doing that, might as well stick with C.

Otherwise, the C++ code is something like this:[code]
std::vector<unsigned char> buffer;
std::vector<unsigned char>::iterator itr = buffer.begin();
std::advance(itr, 8);

for (int i = 0; i < 4; i++) { // hard-coded to 4 (or 8), since cypher doesn't care about 32/64 bits
*itr = (unsigned char) (value & 0xff); // should probably use a proper cast
value /= 256; // depends on the type of 'value'
itr++;
}[/code]
Approximately. Untested.

Most of this is pointless, but there is a ton of gotchas.
- alignment requirements, on most non-x86 architectures writing to non-aligned address fails
- endianess - if just casting an int may result in different order (above is actually serialization problem)
- actually using iterators, instead of mangling pointers. Perhaps a non-issue in above case, but definitely not something iterators are for
If using raw pointers, memcpy would be *much* preferred to assigning to cast, but suffers from endianess issues.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this