c/c++ bytes与int,short,long,float,double相互转换

template
static T bytes2T(unsigned char *bytes)
{
    T res = 0;
    int n = sizeof(T);
    memcpy(&res, bytes, n);
    return res;
}

template
static unsigned char * T2bytes(T u)
{
    int n = sizeof(T);
    unsigned char* b = new unsigned char[n];
    memcpy(b, &u, n);
    return b;
}
//  相关测试代码
//    int d = 267;
//    unsigned char *p = T2bytes(d);
//    for(int i = 0; i //    {
//        printf("p[%d]=0xX\n", i, p[i]);
//    }
//    d = bytes2T(p);
//    printf("d=%d\n", d);
//    delete []p;
//
//    float f = 257.1;
//    p = T2bytes(f);
//    for(int i = 0; i //    {
//        printf("p[%d]=X\n", i, p[i]);
//    }
//    f = bytes2T(p);
//    printf("f=%.1f\n", f);
//    delete []p;

你可能感兴趣的:(编程,学习)