Reputation: 9579
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
Upvotes: 3
Views: 15288
Reputation: 15756
Using Guava:
ByteString byteStringFromInt(int in) {
return ByteString.copyFrom(Ints.toByteArray(in));
}
Upvotes: 0
Reputation: 91
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);
Upvotes: 4
Reputation: 1911
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.
Upvotes: 3