Endianness


#1

I get binary values from Postgres (use libpq with socket connection).

var myInt4 : CPointer<ByteVar>?
myInt4 = PQgetvalue(set, row, column)?.reinterpret<IntVar>()[0] ?: 0
Result: instead of 1 -> 1918959665, 2 -> 1918959666

The binary representation of INT4 is in network byte order, which we’d better coerce to the local byte order.
How is the endianness implemented in Kotlin/Native?


#2

I’d be very surprised if datatypes would not be in native byte order (of the machine architecture). Looking at the language/standard library I don’t think byte order is exposed to users (who don’t use native C to get at this stuff().


#3

@levcom: I’m researching the effort required to wrap libpq for use with Kotlin. I’m about to tackle this very issue myself in the next hour or so. Here are my notes for some possible solutions for swapping the byteorder natively before passing values to kotlin.

Answers from SO worth investigating:

Relevant blogs

From the docs

I’m pretty sure one or more of these should be suitable.

Good luck! I’d be interested to know how you make out. Feel free to point me to any open source repos you’d like to share/collaborate on.


#4

On the JVM it can be queried: https://docs.oracle.com/javase/7/docs/api/java/nio/ByteOrder.html

And the proper way to convert byte ordering on the JVM is using a NIO buffer: https://www.javamex.com/tutorials/io/nio_byte_order.shtml

For Kotlin Javascript or Native, I can’t help you.

And I see now the OP was tlaking about Native.


#5

I studied examples EchoServer.kt and other exam. with native C-functions. I use ntohl/htonl functions from package platform.posix.*

 val value = PQgetvalue(res, j, i)?.let {
                        val v = it.reinterpret<IntVar>().pointed.value
                        val result = ntohl(v)
                        result
                    } ?: 0