3

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

2
  • seems 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 Commented Sep 5, 2012 at 8:37
  • Hava you considered writing the Byte then writing the Protocol-buffer message. As Nikolay said, Protocol-Buffers controls what is written in the message Commented Sep 5, 2012 at 22:57

3 Answers 3

4
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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

Using Guava:

ByteString byteStringFromInt(int in) {
  return ByteString.copyFrom(Ints.toByteArray(in));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.