简体   繁体   中英

How to convert bytes from NSDATA to BigInt16?

I have a NSDATA that is an audio buffer (BIG_ENDIAN), I am trying to get every 2 bytes of the buffer and convert it to an int_16 format to apply a codec in these results.. I am trying the following:

-(NSData*)encodeSample:(NSData*)buffer
{

NSMutableData *backValue = [[NSMutableData alloc] init];

for (int i = 0; i < [buffer length]; i+=4) 
{

    if ( i+4 > [buffer length] )
    {
        break;
    }
    else 
    {

        NSRange range = {i,2};

        int16_t temp1 = OSReadBigInt16([buffer subdataWithRange:range], 0);
        int result1  = [self encode:temp1] & 0x0F; //codec call
        NSRange range2 = {i+2,2};
        int temp2 = OSReadBigInt16([buffer subdataWithRange:range2], 0);
        int result2 = [self encode:temp2] & 0x0F;
        Byte finalValue = (Byte) ((result1 << 4) | result2);

        [backValue appendBytes:&valorFinal length:sizeof(valorFinal)];

    }

I was reading the apple documentation of the function OSReadBigInt16, and I think that it doesn't work with NSDATA, and I don't know what to do to get the correct value.

Someone have an idea about how to get bytes from nsdata and convert it to int_16?

See the Byte Ordering functions in the Foundation Functions documentation. There are a lot of functions like NSSwapIntToHost() and NSSwapShort()

To directly access the bytes the NSData instance is storing, you have to send it a -bytes message, which will return a const void *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM