Tôi giả định rằng dữ liệu đầu vào của bạn là nhị phân (không phải văn bản) và bạn muốn trích xuất khối dữ liệu nhị phân từ nó. Tất cả mà không cần tạo bản sao dữ liệu đầu vào của bạn.
Bạn có thể kết hợp boost::iostreams::basic_array_source
và boost::iostreams::stream_buffer
(từ Boost.Iostreams) với boost::archive::binary_iarchive
(từ Boost.Serialization) để có thể sử dụng khai thác >> khai thác thuận tiện để đọc khối dữ liệu nhị phân.
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_iarchive.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> buffer(dataPtr, sizeof(data));
boost::archive::binary_iarchive archive(buffer, boost::archive::no_header);
uint16_t word1, word2;
archive >> word1 >> word2;
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
Với GCC 4.4.1 trên AMD64, nó kết quả đầu ra:
1234,5678
Boost.Serialization là rất mạnh mẽ và biết làm thế nào để serialize tất cả các loại cơ bản, chuỗi, và thậm chí cả các container STL. Bạn có thể dễ dàng làm cho các loại của bạn serializable. Xem tài liệu. Ẩn ở đâu đó trong các nguồn Boost.Serialization là một ví dụ về một kho lưu trữ nhị phân di động biết cách thực hiện trao đổi thích hợp cho tính cuối cùng của máy. Điều này có thể hữu ích cho bạn.
Nếu bạn không cần fanciness của Boost.Serialization và rất vui khi được đọc dữ liệu nhị phân trong một fread() - loại thời trang, bạn có thể sử dụng basic_array_source
theo một cách đơn giản hơn:
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream<Device> stream(dataPtr, sizeof(data));
uint16_t word1, word2;
stream.read((char*)&word1, sizeof(word1));
stream.read((char*)&word2, sizeof(word2));
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
tôi nhận được cùng một đầu ra với chương trình này.
Nguồn
2010-01-17 05:20:49
Phiên bản MSVC nào? > 6, tôi hy vọng. ;) –
MSVC 9.0 aka 2008 –
Tôi nghĩ rằng giải pháp của bạn là tốt. :) http://stackoverflow.com/questions/1448467/initializing-ac-stdistringstream-from-an-in-memory-buffer/1449527#1449527 –