0

I am very new to programming. Sorry if it's a too beginner question.

I am studying protocol buffers for homework. and I don't know how to get bytes from Message.

Here is the exapmple below from Google Protocol Buffers Documentation,

message Test1 {
  required int32 a = 1;
}

In an application, you create a Test1 message and set a to 150. You then serialize the message to an output stream. If you were able to examine the encoded message, you'd see three bytes:

08 96 01

I am using Eclipse and Java. I created code below.

package com.example.tutorial;

import java.util.Scanner;

import com.example.tutorial.TestProtos.Test1;
import com.example.tutorial.TestProtos.Test1OrBuilder;

public class TestByte {
    public static void main(String[] args) throws Exception{

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");  
        int a = sc.nextInt();
        Test1.Builder t = Test1.newBuilder();
        Test1 obj = t.setA(a).build();
        byte[] arr = obj.toByteArray();

        System.out.println("byte: "+arr);

when I enter '150', it gives me

byte: [B@45ee12a7      

I want to get three bytes like the example in google documentation. I am asking how to get the bytes from encoded message using protocol buffers.

can anyone tell me how? Thank you!!

Eunmi Kong
  • 33
  • 5
  • 1
    While the duplicate mentioned will get the OP the output they desire, it will not help OP to learn the Protobuf API at all (which appears to be their goal). Consider looking at the [MessageLite javadocs](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite). Specifically the methods `toByteString()` and `writeTo()` will be of interest. – rmlan Jan 02 '18 at 17:46
  • Your protobuf code is correct, however the `byte[]` result can not be printed using `System.out.println("byte: "+arr);`. You have to encode it as hex or base64 to print a byte array. – Robert Jan 02 '18 at 18:42

1 Answers1

-1

Try

System.out.println(Arrays.toString(obj));

OR

System.out.println(Arrays.toString(arr));
Mahesh_Loya
  • 2,743
  • 3
  • 16
  • 28
  • This answer is not "You then serialize the message to an output stream". – rmlan Jan 02 '18 at 17:37
  • @rmlan Can you please throw more light on this.I am not getting what you want to say, it will be helpful to me for future reference..thnx – Mahesh_Loya Jan 02 '18 at 17:39
  • Assuming that the user's goal is to learn to use the Protobuf API, there are better usages of the API that can get the output desired by OP. You answer would technically get the output desired, but it is not a great usage of the provided API. See my comment on the question for more info. – rmlan Jan 02 '18 at 17:49