toBytes static method

ByteArray toBytes(
  1. IBuffInfo buff
)

将buff转换为二进制

Implementation

static ByteArray toBytes(IBuffInfo buff) {
  ByteArray bytes = ByteArray();
  bytes.endian = Endian.little;
  bytes.writeByte(buff.type);

  // 基本数据类型
  if (buff.type == BuffType.byteType ||
      buff.type == BuffType.unsignedByteType) {
    bytes.writeByte(buff.value as int);
  } else if (buff.type == BuffType.shortType ||
      buff.type == BuffType.unsignedShortType) {
    bytes.writeShort(buff.value as int);
  } else if (buff.type == BuffType.intType) {
    bytes.writeInt(buff.value as int);
  } else if (buff.type == BuffType.unsignedIntType) {
    bytes.writeUnsignedInt(buff.value as int);
  } else if (buff.type == BuffType.int64Type) {
    bytes.writeInt64(buff.value as int);
  } else if (buff.type == BuffType.floatType) {
    bytes.writeFloat(buff.value as double);
  } else if (buff.type == BuffType.doubleType) {
    bytes.writeDouble(buff.value as double);
  } else if (buff.type == BuffType.stringType) {
    bytes.writeUTF(buff.value as String);
  } else if (buff.type == BuffType.longstringType) {
    ByteArray strBytes = ByteArray();
    strBytes.writeUTFBytes(buff.value as String);
    strBytes.position = 0;
    bytes.writeInt(strBytes.length);
    bytes.writeBytes(strBytes, 0, strBytes.length);
  } else if (buff.type == BuffType.bytesType) {
    bytes.writeInt((buff.value as ByteArray).length);
    bytes.writeBytes(
        buff.value as ByteArray, 0, (buff.value as ByteArray).length);
  } else if (buff.type == BuffType.booleanType) {
    bytes.writeBoolean(buff.value as bool);
  } else if (buff.type == BuffType.objectType) {
    List<IBuffInfo> atts = (buff as IBuffObject).attributes;
    bytes.writeShort(atts.length);
    for (int i = 0; i < atts.length; i++) {
      ByteArray attBytes = BuffBytesUtil.toBytes(atts[i]);
      bytes.writeBytes(attBytes, 0, attBytes.length);
    }
  } else if (buff.type == BuffType.listType) {
    List<IBuffInfo> items = (buff as IBuffList).items;
    bytes.writeShort(items.length);
    for (int i = 0; i < items.length; i++) {
      ByteArray itemBytes = BuffBytesUtil.toBytes(items[i]);
      bytes.writeBytes(itemBytes, 0, itemBytes.length);
    }
  }
  return bytes;
}