Note that there are some explanatory texts on larger screens.

plurals
  1. POSending a Java UUID to C++ as bytes and back over TCP
    primarykey
    data
    text
    <p>I'm trying to send a Java UUID to C++, where it will be used as a GUID, then send it back and see it as a UUID, and I'm hoping to send it across as just 16 bytes.</p> <p>Any suggestions on an easy way to do this?</p> <p>I've got a complicated way of doing it, sending from Java to C++, where I ask the UUID for its least and most significant bits, write this into a ByteBuffer, and then read it out as bytes.</p> <p>Here is my silly-complicated way of getting 2 longs out of a UUID, sending them to C++:</p> <p>Java</p> <pre><code>public static byte[] asByteArray(UUID uuid) { long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); byte[] buffer = new byte[16]; for (int i = 0; i &lt; 8; i++) { buffer[i] = (byte) (msb &gt;&gt;&gt; 8 * (7 - i)); } for (int i = 8; i &lt; 16; i++) { buffer[i] = (byte) (lsb &gt;&gt;&gt; 8 * (7 - i)); } return buffer; } byte[] bytesOriginal = asByteArray(uuid); byte[] bytes = new byte[16]; // Reverse the first 4 bytes bytes[0] = bytesOriginal[3]; bytes[1] = bytesOriginal[2]; bytes[2] = bytesOriginal[1]; bytes[3] = bytesOriginal[0]; // Reverse 6th and 7th bytes[4] = bytesOriginal[5]; bytes[5] = bytesOriginal[4]; // Reverse 8th and 9th bytes[6] = bytesOriginal[7]; bytes[7] = bytesOriginal[6]; // Copy the rest straight up for ( int i = 8; i &lt; 16; i++ ) { bytes[i] = bytesOriginal[i]; } // Use a ByteBuffer to switch our ENDIAN-ness java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(16); buffer.order(java.nio.ByteOrder.BIG_ENDIAN); buffer.put(bytes); buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN); buffer.position(0); UUIDComponents x = new UUIDComponents(); x.id1 = buffer.getLong(); x.id2 = buffer.getLong(); </code></pre> <p>C++</p> <pre><code> google::protobuf::int64 id1 = id.id1(); google::protobuf::int64 id2 = id.id2(); char* pGuid = (char*) &amp;guid; char* pGuidLast8Bytes = pGuid + 8; memcpy(pGuid, &amp;id1, 8); memcpy(pGuidLast8Bytes, &amp;id2, 8); </code></pre> <p>This works, but seems way too complex, and I can't yet get it working in the other direction.</p> <p>(I'm using google protocol buffers to send the two longs back and forth)</p> <ul> <li>Alex</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload