即时通讯之输入流中读取基本数据

相应的和写入一样,下面将读取的接口陈列如下:

读取 1 byte

- (int8_t)readChar;
{
    int8_t v;
    [data getBytes:&v range:NSMakeRange(len, 1)];
    len++;
    return (v & 0x0FF);
}

读取 2 byte

- (int16_t)readShort;
{
    int32_t ch1 = [self read];
    int32_t ch2 = [self read];
    if ((ch1 | ch2) < 0) {
        @throw [NSException exceptionWithName:@"Exception" reason:@"EOFException" userInfo:nil];
    }
    return (int16_t)((ch1 << 8) + (ch2 << 0));
}

读取 4 byte

- (int32_t)readInt;
{
    int32_t ch1 = [self read];
    int32_t ch2 = [self read];
    int32_t ch3 = [self read];
    int32_t ch4 = [self read];
    if ((ch1 | ch2 | ch3 | ch4) < 0){
        @throw [NSException exceptionWithName:@"Exception" reason:@"EOFException" userInfo:nil];
    }
    return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}

读取 8 byte

- (int64_t)readLong; { int8_t ch[8]; [data getBytes:&ch range:NSMakeRange(len,8)]; len += 8; return (((int64_t)ch[0] << 56) + ((int64_t)(ch[1] & 255) << 48) + ((int64_t)(ch[2] & 255) << 40) + ((int64_t)(ch[3] & 255) << 32) + ((int64_t)(ch[4] & 255) << 24) + ((ch[5] & 255) << 16) + ((ch[6] & 255) << 8) + ((ch[7] & 255) << 0)); }

BCD时钟转换

- (BDSTime)readBCDTime
{
    struct BDSTime bcdTime;
    Byte year[2];
    Byte month[1], day[1], hour[1], min[1], sec[1];

    [data getBytes:&year range:NSMakeRange(len, sizeof(year))];
    len += sizeof(year);

    [data getBytes:&month range:NSMakeRange(len, sizeof(month))];
    len += sizeof(month);

    [data getBytes:&day range:NSMakeRange(len, sizeof(day))];
    len += sizeof(day);

    [data getBytes:&hour range:NSMakeRange(len, sizeof(hour))];
    len += sizeof(hour);

    [data getBytes:&min range:NSMakeRange(len, sizeof(min))];
    len += sizeof(min);

    [data getBytes:&sec range:NSMakeRange(len, sizeof(sec))];
    len += sizeof(sec);

    bcdTime.year = [self readBCDToYear:year];

    bcdTime.month = bcdToInt(month, sizeof(month));
    bcdTime.day = bcdToInt(day, sizeof(day));
    bcdTime.hour = bcdToInt(hour, sizeof(hour));
    bcdTime.min = bcdToInt(min, sizeof(min));
    bcdTime.sec = bcdToInt(sec, sizeof(sec));

    return bcdTime;
}

///bcd转int
unsigned int  bcdToInt(const unsigned char *bcd, int length)
{
    int tmp;
    unsigned int dec = 0;

    for(int i = 0; i < length; i++)
    {
        tmp = ((bcd[i] >> 4) & 0x0F) * 10 + (bcd[i] & 0x0F);
        dec += tmp * pow(100, length - 1 - i);
    }

    return dec;
}

- (int16_t)readBCDToYear:(Byte *)dt
{
    Byte *year = dt;
    Byte y_high = year[0];
    Byte y_low = year[1];

    int16_t high = bcdToInt(&y_high, sizeof(y_high));
    int16_t low = bcdToInt(&y_low, sizeof(y_low));
    return high*100+low;
}

你可能感兴趣的:(数据,即时通讯)