c向java发送字节_将Java UUID作为字节发送到C并通过TCP返回

我有工作.

我不是以两个long形式发送,而是以字节为单位发送,这是Java代码:

public static UUID fromBytes( ByteString byteString)

{

byte[] bytesOriginal = byteString.toByteArray();

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 < 16; i++ )

{

bytes[i] = bytesOriginal[i];

}

return toUUID(bytes);

}

public static ByteString toBytes( UUID uuid )

{

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 < 16; i++ )

{

bytes[i] = bytesOriginal[i];

}

return ByteString.copyFrom(bytes);

}

private static byte[] asByteArray(UUID uuid)

{

long msb = uuid.getMostSignificantBits();

long lsb = uuid.getLeastSignificantBits();

byte[] buffer = new byte[16];

for (int i = 0; i < 8; i++) {

buffer[i] = (byte) (msb >>> 8 * (7 - i));

}

for (int i = 8; i < 16; i++) {

buffer[i] = (byte) (lsb >>> 8 * (7 - i));

}

return buffer;

}

private static UUID toUUID(byte[] byteArray) {

long msb = 0;

long lsb = 0;

for (int i = 0; i < 8; i++)

msb = (msb << 8) | (byteArray[i] & 0xff);

for (int i = 8; i < 16; i++)

lsb = (lsb << 8) | (byteArray[i] & 0xff);

UUID result = new UUID(msb, lsb);

return result;

}

这样,字节可以直接在C端使用.我想可以在任一端完成字节顺序的切换.

C

memcpy(&guid, data, 16);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值