Objective-c(iOS)中的字节数组为短值,反之亦然

时间:2015-01-20 15:24:29

标签: ios objective-c

我将Byte数组(NSMutableData)转换为short值。

+(short)byteArrayToShort:(NSMutableData *)paRawBytes offset:(int)piOffset{

int iRetVal = -1;

int8_t *byteArray = [paRawBytes mutableBytes];

int iLow;
int iHigh;

if(CFByteOrderGetCurrent() == CFByteOrderBigEndian)
{
    iLow  = byteArray[piOffset + 1];
    iHigh = byteArray[piOffset + 0];
}
else
{
    iLow  = byteArray[piOffset + 0];
    iHigh = byteArray[piOffset + 1];
}

// Merge high-order and low-order byte to form a 16-bit double value.
iRetVal = (iHigh << 8) | (0xFF & iLow);

return (short)iRetVal;
}

在iOS中这是正确的方法吗?

Ans也是,我将Short值转换为Byte数组(NSMutableData)。

+(int8_t *)shortToByteArray:(short)piValueToConvert
{
int8_t * aRetVal;

Byte iLowest;
Byte iHigh;

iLowest = (Byte)(piValueToConvert & 0xFF);
iHigh    = (Byte)((piValueToConvert >> 8) & 0xFF);

if(CFByteOrderGetCurrent() == CFByteOrderBigEndian)
{
    aRetVal[1] = iLowest;
    aRetVal[0] = iHigh;
}
else
{
    aRetVal[0] = iLowest;
    aRetVal[1] = iHigh;
}


return aRetVal;

}

请建议我这是否正确...... 提前致谢

0 个答案:

没有答案