Bonjour,
suite à cette discutions :http://www.developpez.net/forums/d61...-lire-fichier/
je me suis amusé à faire des template pour résoudre le problème de endian.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <sstream>
 
template<typename T,int N =sizeof(T)>
struct reader
{
    static T read(std::istream & is)
    {
     /*  BOOST_STATIC_ASSERT
           (
           sizeof(T)<= sizeof(unsigned long long)
           &&
           N <= sizeof(unsigned long long)
           );*/
 
       unsigned char buf[N] = {0};
       is.read(reinterpret_cast<char*>(buf),N);
       unsigned long long tmp(0);
       for (int i= 0;i<N;++i)
       {
            tmp |= static_cast<unsigned long long>(buf[i])<<8*(N-1-i);
       }
       return *reinterpret_cast<T*>(&tmp);
    }
};
 
template<typename T,int N =sizeof(T)>
struct writer
{
    static void write(std::ostream & os,const T &t)
    {
    /*   BOOST_STATIC_ASSERT
          (
           sizeof(T)<= sizeof(unsigned long long)
           &&
           N <= sizeof(unsigned long long)
           );*/
       unsigned char buf[N];
 
       const unsigned long long *tmp =   reinterpret_cast<const unsigned long long*>(&t);
       for (int i= 0;i<N;++i)
       {
            buf[i] = static_cast<unsigned char>(*tmp >>8*(N-1-i));
       }
       os.write((char*)buf,N);
    }
};
 
int main(int argc, char* argv[])
{
    std::ostringstream os(std::ios::binary);
 
    writer<float>::write(os,100025.8644f);
    writer<int>::write(os,10);
    writer<char>::write(os,'a');
    writer<double>::write(os,125863.4565465);
 
    std::istringstream is(os.str(),std::ios::binary);
    std::cout<<reader<float>::read(is)<<std::endl;
    std::cout<<reader<int>::read(is)<<std::endl;
    std::cout<<reader<char>::read(is)<<std::endl;
 
    double b = reader<double>::read(is);
 
 
	return 0;
}
J'aurais trois questions :
1- je ne peut gérer que les type dont la taille est <=unsigned long long. Comment faire pour faire le cas de plus grand type? (peut être y en as t'il pas)
2- y as t'il un moyen pour trouver le type unsigned le plus proche de sizeof(T)
3- Qu'en pensez vous?