68

Is there an equivalent to int8 or byte type in proto buffs? I would like to send a byte array object.

Usman Ismail
  • 17,999
  • 14
  • 83
  • 165
  • 1
    Be careful with the size the you send: "As a general rule of thumb, if you are dealing in messages **larger than a megabyte each**, it may be time to consider an alternate strategy." - https://developers.google.com/protocol-buffers/docs/techniques – AlikElzin-kilaka Jul 14 '20 at 09:03

3 Answers3

88

https://developers.google.com/protocol-buffers/docs/proto3#scalar

bytes: May contain any arbitrary sequence of bytes no longer than 232.

Noel Yap
  • 18,822
  • 21
  • 92
  • 144
Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
  • 1
    Unfortunately still serializes to strings in java. But thanks for the link. – Usman Ismail Dec 07 '11 at 19:36
  • 14
    No, according to the documentation the corresponding Java type is `ByteString`. You can get the byte array itself using the `toByteArray` method. – JesperE Dec 08 '11 at 08:09
  • In case you already have the byte[] array just use LiteralByteString so you don't have to copy it over. – marios Feb 25 '18 at 00:12
11

If you are looking to store a single byte, however, I would suggest using the Int32. It is a 'variant' type variable that will change size depending on the data that is stored in it. So if you are storing a single byte, it will be the smallest structure. The byteS data type is actually quite large in comparison. This is because the bytes structure holds data such as index length and other properties.

On serialization, I noticed a size difference of about half when switching from a single byte stored in a byteS to an int32.

Note, however, that this does not apply to multiple bytes being stored in the byteS, which I suspect will be much smaller than storing individual Int32.

Misha Mengisen
  • 111
  • 1
  • 2
8

The ByteString class provides methods to convert a few types to protobuff type "bytes" or ByteString

public static ByteString CopyFrom(params byte[] bytes);
public static ByteString CopyFrom(string text, Encoding encoding);
Coder2013333
  • 139
  • 1
  • 9