本文介绍了在C中将Char数组转换为Long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能看起来很愚蠢,但是请指导我我有一个将长数据转换为char数组的功能

This question may looks silly, but please guide meI have a function to convert long data to char array

void ConvertLongToChar(char *pSrc, char *pDest)
{
    pDest[0] = pSrc[0];
    pDest[1] = pSrc[1];
    pDest[2] = pSrc[2];
    pDest[3] = pSrc[3];
}

我这样调用上面的函数

long lTemp = (long) (fRxPower * 1000);
ConvertLongToChar ((char *)&lTemp, pBuffer);

哪个工作正常.我需要类似的功能来逆转该过程.将char数组转换为long.我不能使用atol或类似功能.

Which works fine.I need a similar function to reverse the procedure. Convert char array to long.I cannot use atol or similar functions.

推荐答案

这是让您将字节序与其他函数进行匹配的负担,这是一种方法:

Leaving the burden of matching the endianness with your other function to you, here's one way:

unsigned long int l = pdest[0] | (pdest[1] << 8) | (pdest[2] << 16) | (pdest[3] << 24);

为了安全起见,这是相应的其他方向:

Just to be safe, here's the corresponding other direction:

unsigned char pdest[4];
unsigned long int l;
pdest[0] = l         & 0xFF;
pdest[1] = (l >>  8) & 0xFF;
pdest[2] = (l >> 16) & 0xFF;
pdest[3] = (l >> 24) & 0xFF;

char[4]到多头和后头完全是可逆的;对于最大2 ^ 32-1的值,从长到char[4]并返回是可逆的.

Going from char[4] to long and back is entirely reversible; going from long to char[4] and back is reversible for values up to 2^32-1.

请注意,所有这些仅针对无符号类型进行了明确定义.

Note that all this is only well-defined for unsigned types.

(如果您从左到右阅读pdest,我的示例是 little 字节序).

(My example is little endian if you read pdest from left to right.)

附录:我还假设CHAR_BIT == 8.通常,用代码中的CHAR_BIT的倍数替换8的倍数.

Addendum: I'm also assuming that CHAR_BIT == 8. In general, substitute multiples of 8 by multiples of CHAR_BIT in the code.

这篇关于在C中将Char数组转换为Long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:52