将双重价值从小恩迪安转换为大恩迪安

Convert double value from little endian to Big endian

本文关键字:转换      更新时间:2023-10-16

我正在从小恩迪安转换为大恩迪安,然后回到小检查
是对还是错,请帮助我

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>

double dx = 122992001003000;
//A method little to big endian
double bEndian(double d) {
    int *p0 = (int *) &d;
    int *p1 = p0 + 1;
    printf("1: %x %xn", *p0, *p1);
    int tmp = *p1;
    *p1 = htonl(*p0);
    *p0 = htonl(tmp);
    printf("2: %x %xn", *p0, *p1);
    return *(double *)p0;
}
//A method  big to little endian
double lEndian(double d) {
    int *p0 = (int *) &d;
    int *p1 = p0 + 1;
    printf("3: %x %xn", *p0, *p1);
    int tmp = *p1;
    *p1 = ntohl(*p0);
    *p0 = ntohl(tmp);
    printf("4: %x %xn", *p0, *p1);
    return *(double *)p0;
}
int main (int argc, char *argv[]) 
{       
    double d1 = bEndian(dx);
    double d2 = lEndian(d1);
    printf("5: %.0fn", d2);
    if ((*(double*) &d2) == dx)
      printf("6: %.0lfn", *(double*) &d2);
    else
      printf("7:%dn", d2);
    return 0;
}

有时给我结果122992001003129为什么? 同样使用NTOHL或HTONL没有差异?仅是为了惯例吗即网络主机和主机网络

这是一个可以改变dendianness的函数。

#include <algorithm>
#include <cstdio>
template <class T>
T change_endian(T in)
{
    char* const p = reinterpret_cast<char*>(&in);
    for (size_t i = 0; i < sizeof(T) / 2; ++i)
        std::swap(p[i], p[sizeof(T) - i - 1]);
    return in;
}
int main()
{
    double d = 122992001003000;
    printf("%fn", d);
    d = change_endian(d);
    printf("%fn", d);
    d = change_endian(d);
    printf("%fn", d);
}

输出:

122992001003000.000000
0.000000
122992001003000.000000

Easy:

#include <endian.h>
#include <stdint.h>
double  src_num = YOUR_VALUE;
int64_t tmp_num = htobe64(le64toh(*(int64_t*)&src_num));
double  dst_num = *(double*)&tmp_num;

但是,有某些怪癖:https://en.wikipedia.org/wiki/endianness#floating_point_point

typedef union
{
    double d;
    unsigned char s[8];
} Union_t;
// reverse little to big endian or vice versa as per requirement
double reverse_endian(double in)
{
    int i, j;
    unsigned char t;
    Union_t val;
    val.d = in;
    // swap MSB with LSB etc.
    for(i=0, j=7; i < j; i++, j--)
    {
        t = val.s[i];
        val.s[i] = val.s[j];
        val.s[j] = t;
    }
    return val.d;
}

四个字节的简单反转应起作用

double ReverseDouble( const double indouble )
{
   double retVal;
   char *doubleToConvert = ( char* ) & indouble;
   char *returndouble = ( char* ) & retVal;
   // swap the bytes into a temporary buffer
   returndouble[0] = doubleToConvert[3];
   returndouble[1] = doubleToConvert[2];
   returndouble[2] = doubleToConvert[1];
   returndouble[3] = doubleToConvert[0];
   return retVal;
}