信息的表示和处理

字节序

字节序 (Endianness) 面向 多字节数值类型 (Int16, Int32, Int64) 定义

  • 小端(littleEndian): 多字节数值类型的数值低位存储在内存低位,小端易存取易计算,多用于存储
  • 大端(bigEndian): 数值低位存储在内存高位,大端易阅读,多用于网络传输
// iOS字节序是小端
withUnsafeBytes(of: UInt32(0x01_02_03_04)) { p in
    p.forEach { byte in
        print(byte) // 4 3 2 1
    }
}

// 转为大端
withUnsafeBytes(of: UInt32(0x01_02_03_04).bigEndian) { p in
    p.forEach { byte in
        print(byte) // 1 2 3 4
    }
}

整数表示

整数类型十进制二进制原码反码补码计算机中实际的记录
Int300110011
Int-3-00111011110011011101
UInt300110011
withUnsafeBytes(of: 3) { p in
    print(String(p[0], radix: 2)) // 00000011
}

withUnsafeBytes(of: -3) { p in
    print(String(p[0], radix: 2)) // 11111101
}

浮点数表示

浮点数类型十进制二进制科学计数阶数尾数计算机中实际的记录
Float3.62511.1011.1101 * 2^11 + 0111111111010100000001101
Float-3.625-11.101-1.1101 * 2^11 + 0111111111011100000001101
Double3.62511.1011.1101 * 2^11 + 0111111111111010100000000001101
Double-3.625-11.101-1.1101 * 2^11 + 0111111111111011100000000001101
withUnsafeBytes(of: Float(3.625)) { p in
    print(String(UInt16(p[3]) << 8 + UInt16(p[2]), radix: 2)) // 0100000001101000
}
withUnsafeBytes(of: Float(-3.625)) { p in
    print(String(UInt16(p[3]) << 8 + UInt16(p[2]), radix: 2)) // 1100000001101000
}

withUnsafeBytes(of: 3.625) { p in
    print(String(UInt16(p[7]) << 8 + UInt16(p[6]), radix: 2)) // 0100000000001101
}
withUnsafeBytes(of: -3.625) { p in
    print(String(UInt16(p[7]) << 8 + UInt16(p[6]), radix: 2)) // 1100000000001101
}