即时通讯之基本数据写入到输出流中

在做IM或蓝牙传输的项目中,难免会有这样那样的数据转码的情况,下面就将我在项目中用到的一些转换接口总结一下,将其陈列出来,希望能够帮助后来者。

将 1 byte 数值写入输出流中, 先写入高位

- (void)writeChar:(int8_t)v;
{
    int8_t ch[1];
    ch[0] = (v & 0x0FF);
    [data appendBytes:ch length:sizeof(ch)];
    len++;
}

将 2 byte 数值写入输出流中, 先写入高位

- (void)writeShort:(int16_t)v;
{
    int8_t ch[2];
    ch[0] = (v & 0x0FF00) >> 8;
    ch[1] = (v & 0x0FF);
    [data appendBytes:ch length:sizeof(ch)];
    len += sizeof(ch);
}

将 4 byte 数值写入输出流中, 先写入高位

- (void)writeInt:(int32_t)v;
{
    int8_t ch[4];
    for (int32_t i = 0; i < sizeof(ch); i++) {
        ch[i] = ((v >> ((3-i) * 8)) & 0x0FF);
    }
    [data appendBytes:ch length:sizeof(ch)];
    len += sizeof(ch);
}

将 8 byte 数值写入输出流中, 先写入高位

- (void)writeLong:(int64_t)v;
{
    int8_t ch[8];
    for (int32_t i = 0; i < sizeof(ch); i++) {
        ch[i] = ((v >> ((7-i) * 8)) & 0x0FF);
    }
    [data appendBytes:ch length:sizeof(ch)];
    len += sizeof(ch);
}

将 BCD时钟 写入输出流中

- (Byte)int_toBCD:(unsigned int)v
{
    Byte d1 = v / 10;
    Byte d2 = v % 10;
    Byte d = (d1 << 4) | d2;
    return d;
}

- (void)writeBCDTime:(BDSTime *)time;
{
    //write year
    [self writeYearBCDTime:time -> year];
    //write month
    [self writeOtherBCDTime:time -> month];
    //write day
    [self writeOtherBCDTime:time -> day];
    //write hour
    [self writeOtherBCDTime:time -> hour];
    //write min
    [self writeOtherBCDTime:time -> min];
    //write sec
    [self writeOtherBCDTime:time -> sec];
}

- (void)writeYearBCDTime:(int16_t)v
{
    unsigned int high, low;
    high = v / 100;
    low = v % 100;

    int8_t ch[2];
    ch[0] = int_toBCD(high);
    ch[1] = int_toBCD(low);
    [data appendBytes:ch length:sizeof(ch)];
    len += sizeof(ch);
}

- (void)writeOtherBCDTime:(int8_t)v
{
    int8_t ch[1];
    ch[0] = int_toBCD(v);
    [data appendBytes:ch length:sizeof(ch)];
    len += sizeof(ch);
}

下载地址:BDWRDataDemo

你可能感兴趣的:(iOS开发)