インスタント通信の入力ストリームから基本データを読み出す


対応するインタフェースは、書き込みと同様に、次のように表示されます.
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;
}