c++ 在Kotlin中处理endianess

yacmzcpb  于 4个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(69)

我试图在Android应用程序中对字节数组进行格式化(在MacOS上使用M1芯片编译)。字节来自网络,由运行在Ubuntu上的C应用程序生成。在C应用程序中,我检查了它使用的是Little Endian:

bool isBigEndian()
{
    uint16_t word = 1;                      // 0x0001
    uint8_t *first_byte = (uint8_t *)&word; // points to the first byte of word
    return !(*first_byte);                  // true if the first byte is zero
}

// Check:
if (isBigEndian())
    printf("Big endian\n");
else
    printf("Little endian\n");

字符串
以上代码用C++打印出来Little endian
在Kotlin(Android)端,我也检查并看到它也使用了Little Endian,但从字节数组转换的长数字不正确。

fun isLittleEndian(): Boolean {
    return ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN
}

/**
 * Represent 8 bytes of [Long] into byte array
 */
fun Long.toBytes(): ByteArray {
    return ByteBuffer.allocate(Long.SIZE_BYTES).putLong(this).array()
}
fun ByteArray.toLong(): Long {
    return ByteBuffer.wrap(this).long
}
fun test(){
    val longNumber = 1000L
    val isLittleEndian = isLittleEndian() // true
    val bytes = longNumber.toBytes()      // bytes: [0,0,0,0,0,0,3,-24] => Big Endian?
}


C应用程序将长数字1000序列化为[ -24, 3,0,0,0,0,0,0](正确的小端排序),而Kotlin代码将相同的长数字转换为[0,0,0,0,0,0,3,-24](这是大端排序)。
当使用Kotlin从C
应用程序转换字节时,我得到了奇怪的值-1728537831980138496而不是1000
请帮我检查一下我在处理endianess时有没有出错?

oyt4ldly

oyt4ldly1#

allocatewrap方法都将返回一个BIG_ENDIAN缓冲区。您必须调用order将字节序更改为LITTLE_ENDIAN
举例来说:

import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.ByteOrder.BIG_ENDIAN
import java.nio.ByteOrder.LITTLE_ENDIAN

fun Long.toBytes(order: ByteOrder = BIG_ENDIAN): ByteArray {
    return ByteBuffer.allocate(Long.SIZE_BYTES).order(order).putLong(this).array()
}

fun ByteArray.toLong(order: ByteOrder = BIG_ENDIAN): Long {
    return ByteBuffer.wrap(this).order(order).long
}

fun main() { 
    val number = 1000L
    val encoded = number.toBytes(order = LITTLE_ENDIAN)
    val decoded = encoded.toLong(order = LITTLE_ENDIAN)
    
    println("Number  = $number")
    println("Encoded = ${encoded.contentToString()}")
    println("Decoded = $decoded")
}

字符串
输出量:

Number  = 1000
Encoded = [-24, 3, 0, 0, 0, 0, 0, 0]
Decoded = 1000

相关问题