Steefmaester

Découpage et Assemblage d'un float par octets

Jun 3rd, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. //by steef
  2.  
  3. #include <iostream>
  4.  
  5.  
  6. using namespace std;
  7.  
  8. void decoup_float(float val, unsigned char tab[])
  9. {
  10.     unsigned char * ptr_char = reinterpret_cast<unsigned char *>(&val);//ptr sur uchar à l'adresse du float (val)
  11.  
  12.     for (int i = 0; i < sizeof(val); i++) {
  13.  
  14.         tab[i] = static_cast<int>(*(ptr_char + i));//stock la valeur de chaque octets pointer dans un tableau
  15.  
  16.     }
  17.  
  18. }
  19.  
  20. float reconstitution_float(unsigned char tab[])
  21. {
  22.  
  23.     float val;
  24.     unsigned char * ptr_char = reinterpret_cast<unsigned char *>(&val);//ptr sur uchar à l'adresse du float (val)
  25.  
  26.     for (int i = 0; i < sizeof(val); i++) {
  27.  
  28.         *(ptr_char + i) = tab[i] ;//écrit la valeur de chaques octets dans l'emplacement memoire correspondant dans le float
  29.  
  30.     }
  31.  
  32.     return val;
  33.  
  34. }
  35.  
  36. int main()
  37. {
  38.     float val_f = 3.14;
  39.     unsigned char octets[4];
  40.  
  41.     decoup_float(val_f, octets);
  42.  
  43.     cout <<hex<< static_cast<int>(octets[0]) << endl;
  44.     cout << static_cast<int>(octets[1]) << endl;
  45.     cout << static_cast<int>(octets[2]) << endl;
  46.     cout << static_cast<int>(octets[3]) << endl;
  47.  
  48.     cout << reconstitution_float(octets) << endl;
  49.  
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment