1 #ifndef FILEUTIL_HEADER_
2 #define FILEUTIL_HEADER_
6 template <class T
> inline void put(std::ostream
&os
,T i
);
7 template <class T
> inline T
get(std::istream
&is
);
11 template<> inline void put(std::ostream
&os
,Uchar i
) {
14 template<> inline Uchar
get(std::istream
&is
) {
18 template<> inline void put(std::ostream
&os
,Uint16 i
) {
22 template<> inline Uint16
get(std::istream
&is
) {
23 Uint16 res
= get
<Uchar
>(is
);
24 return res
*256+get
<Uchar
>(is
);
27 template<> inline void put(std::ostream
&os
,Uint32 i
) {
28 put
<Uchar
>(os
,i
/(256*256*256));
29 put
<Uchar
>(os
,i
/(256*256)%256);
30 put
<Uchar
>(os
,i
/256%256);
33 template<> inline Uint32
get(std::istream
&is
) {
35 for (int i
=0; i
<4; ++i
)
36 res
= res
*256+get
<Uchar
>(is
);
40 template<> inline void put(std::ostream
&os
,float f
) {
41 ASSERT( sizeof(float)==4 );
42 os
.write( (const char*)&f
, sizeof(float) );
44 template<> inline float get(std::istream
&is
) {
45 ASSERT( sizeof(float)==4 );
47 is
.read( (char*)&result
, sizeof(float) );
51 inline int float01ToBits(Real f
,int bitCount
) {
52 int result
= (int)std::ldexp(f
,bitCount
);
53 return result
==powers
[bitCount
] ? result
-1 : result
;
55 inline Real
float01FromBits(int bits
,int bitCount
) {
56 return std::ldexp( Real(bits
)+Real(0.5), -bitCount
);
60 /** Stream bit-writer - automated buffer for writing single bits */
62 /** Buffered bits, number of buffered bits */
64 /** Used output (byte)stream */
67 /** Constructor just associates the object with the given stream */
68 BitWriter(std::ostream
&stream
)
69 : buffer(0), bufbits(0), os(stream
) {}
70 /** Destructor only flushes the buffer */
74 void putBits(int val
,int bits
) {
75 ASSERT( bits
>0 && 0<=val
&& val
<powers
[bits
] );
76 buffer
+= powers
[bufbits
]*val
;
84 /** Flushes the buffer - sends it to the stream */
92 /** Stream bit-reader - automated buffer for reading single bits */
94 /** Buffered bits, number of buffered bits */
96 /** Used input (byte)stream */
99 /** Constructor just associates the object with the given stream */
100 BitReader(std::istream
&stream
)
101 : buffer(0), bufbits(0), is(stream
) {}
103 int getBits(int bits
) {
105 while (bufbits
<bits
) {
106 buffer
+= powers
[bufbits
]*Uchar(is
.get());
109 int result
= buffer
%powers
[bits
];
110 buffer
/= powers
[bits
];
120 inline bool file2string(const char *name
,std::string
&result
) {
122 ifstream
file( name
, ios_base::binary
|ios_base::in
);
126 file
.seekg(0,ios::end
);
127 int length
= file
.tellg();
133 file
.seekg(0,ios::beg
);
134 file
.read(&res
[0],length
);
135 if (file
.gcount()!=length
)
141 #endif // FILEUTIL_HEADER_