java protobuf how to create ByteString from int
Solution 1
ByteBuffer eventTypeBuffer = ByteBuffer.allocate(1);
eventTypeBuffer.put(0x1c);
eventTypeBuffer.flip();
ByteString eventType = ByteString.copyFrom(eventTypeBuffer);
System.out.println(eventType.size() + " " + eventTypeBuffer.array().length);
Header.Builder mh = Header.newBuilder();
mh.setEventType(eventType);
Solution 2
Consider protobuf message to be a 'black-box' string of bytes. Get the protobuf message out after reading the first byte and then handle the protobuf part.
Create a byte buffer
Byte[] buf = new Byte[100]; //length as per your application
Then give the first byte as per your application (which rejects or accepts messages depending upon the first byte). The rest of the bytes you can fill with the protobuf message.
Nikolay Kuznetsov
Updated on May 25, 2022Comments
-
Nikolay Kuznetsov about 2 years
I would like to use google protobuf in my project.
The point is that I have to set first byte of very message because of underlying code which rejects or accepts the message based on the first byte and it does not know about protobuf.
So this page says https://developers.google.com/protocol-buffers/docs/proto#scalar that I have to use bytes field that corresponds to ByteString in Java.
bytes May contain any arbitrary sequence of bytes. string ByteString
But I do not know how to create ByteString from int value. I have tried this way:
ByteBuffer eventTypeBuffer = ByteBuffer.allocate(1); eventTypeBuffer.put(0x1c); ByteString eventType = ByteString.copyFrom(eventTypeBuffer); System.out.println(eventType.size() + " " + eventTypeBuffer.array().length); Header.Builder mh = Header.newBuilder(); mh.setEventType(eventType);
Does not work properly and println gives 0 1
-
Nikolay Kuznetsov almost 12 yearsseems that protobuf produces specific format of bytes so I can not expect that the first field of type bytes becomes the very first byte of the message
-
Bruce Martin almost 12 yearsHava you considered writing the Byte then writing the Protocol-buffer message. As Nikolay said, Protocol-Buffers controls what is written in the message
-