=?UTF-8?Q?Re=3A_custom_streambuf_implementation=E2=80=8F?=
On Nov 19, 4:01 am, ma740988 <ma740...@gmail.com> wrote:
I'm receiving 60 bytes of data from an interface. For discussion
purposes lets consider.
unsigned char data [ 60 ] = { 0x00, 0x05, 0xFE, 0xCA };
The goal: Store the bytes into an array of unsigned short such that:
typedef std::vector < unsigned short > USHORT_VEC ;
USHORT_VEC us_vec ( 2 ) ;
us_vec [ 0 ] = 0x0005 ;
us_vec [ 1 ] = 0xFECA ;
NOTE: a 'simple' memcpy of the data results in 0x500 and
0xCAFE, for elements 0 and 1 respectively - which is not what
I want. The question: Can I use a custom streambuf
implementation - derived off streambuf to achieve the
objective?
I'll admit that the entire streams facility seems daunting
(even while skimming through Langer/Kreft) so source
snippet/any help appreciated. Thanks
If you already have the data in memory (in an array of unsigned
char), then streambuf is probably not what you're looking for;
streambuf is for sinking and sourcing data, more than anything
else.
All you really need is a simple loop:
template< typename InputIterator, typename OutputIterator >
void
as_short_array(
std::vector< unsigned char >::const_iterator begin,
std::vector< unsigned char >::const_iterator end,
std::back_inserter< std::vector< short > dest )
{
assert( (end - begin) % 2 == 0 );
while ( begin != end ) {
*dest = *begin | (*(begin + 1) << 8);
++ dest;
begin += 2;
}
}
If you want to get a little bit fancier, it would be pretty
simple to create an iterator which does this on the fly, and use
that with std::copy.
--
James Kanze