static byte[] serializeSessionFields(final MemcachedBackupSession session) {

    final byte[] idData = serializeId(session.getIdInternal());

    final byte[] principalData =
        session.getPrincipal() != null ? serializePrincipal(session.getPrincipal()) : null;
    final int principalDataLength = principalData != null ? principalData.length : 0;

    final int sessionFieldsDataLength =
        2 // short value for the version
            // the following might change with other versions, refactoring needed then
            + 2 // short value that stores the dataLength
            + NUM_BYTES // bytes that store all session attributes but the id
            + 2 // short value that stores the idData length
            + idData.length // the number of bytes for the id
            + 2 // short value for the authType
            + 2 // short value that stores the principalData length
            + principalDataLength; // the number of bytes for the principal
    final byte[] data = new byte[sessionFieldsDataLength];

    int idx = 0;
    idx = encodeNum(CURRENT_VERSION, data, idx, 2);
    idx = encodeNum(sessionFieldsDataLength, data, idx, 2);
    idx = encodeNum(session.getCreationTimeInternal(), data, idx, 8);
    idx = encodeNum(session.getLastAccessedTimeInternal(), data, idx, 8);
    idx = encodeNum(session.getMaxInactiveInterval(), data, idx, 4);
    idx = encodeBoolean(session.isNewInternal(), data, idx);
    idx = encodeBoolean(session.isValidInternal(), data, idx);
    idx = encodeNum(session.getThisAccessedTimeInternal(), data, idx, 8);
    idx = encodeNum(session.getLastBackupTime(), data, idx, 8);
    idx = encodeNum(idData.length, data, idx, 2);
    idx = copy(idData, data, idx);
    idx = encodeNum(AuthType.valueOfValue(session.getAuthType()).getId(), data, idx, 2);
    idx = encodeNum(principalDataLength, data, idx, 2);
    copy(principalData, data, idx);

    return data;
  }