Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to ByteString when using protobuf?

I want to convert a string object to ByteString.I have tried to use ByteString.CopyFrom() function to convert,but the return value is always "{Google.ProtocolBuffers.ByteString}".Why? How can I do?

The function i use like this.

The result

like image 587
Boreas Avatar asked Oct 09 '16 13:10

Boreas


People also ask

How does Protobuf serialize string?

The Protobuf serialization mechanism is given through the protoc application, this compiler will parse the . proto file and will generate as output, source files according to the configured language by its arguments, in this case, C++. You can also obtain more information about, reading the section compiler invocation.

What encoding does Protobuf use?

Protobuf strings are always valid UTF-8 strings. See the Language Guide: A string must always contain UTF-8 encoded or 7-bit ASCII text.

How does Protobuf encoding work?

Protobuf categorizes normally used data types into wire types which provides information to find the length of the value. For wire type 2, length is also encoded along with value. Zero values are not transmitted. 0, False, “”, does not take any bytes.


3 Answers

According to the docs, Google.ProtocolBuffers.ByteStreamneeds an encoding to know how to display its content. Use ByteStream.ToString(Encoding encoding) or ByteStream.ToStringUtf8().

like image 64
quimnuss Avatar answered Nov 18 '22 11:11

quimnuss


You can use one of methods from ByteString class to convert string to ByteArray ByteString.copyFromUtf8(stringText).

like image 27
Maneesh K Bishnoi Avatar answered Nov 18 '22 11:11

Maneesh K Bishnoi


Your string has been successfully converted to ByteStream. If you see {Google.ProtocolBuffers.ByteString} in the watch window, it simply means that the ByteStream does not override the ToString method. In short, Visual Studio doesn't know how to display a ByteStream, and therefore just display the type name instead.

That said, there is an overload of the CopyFrom method that allows you to directly use a string:

var APP_DEF_TEA_KEY = ByteString.CopyFrom("e#>&*m16", Encoding.Unicode);
like image 13
Kevin Gosse Avatar answered Nov 18 '22 09:11

Kevin Gosse