I want to parse binary string into message c++

452 views
Skip to first unread message

정등혁

unread,
Jan 3, 2018, 7:02:40 AM1/3/18
to Protocol Buffers
#include <iostream>
#include <fstream>
#include <string>
#include "EncodeMessage.pb.h"
using namespace std;

string HexString2BinaryString(string sHex)
{
string sReturn = "";
int sLen = sHex.length();
for (int i = 0; i < sLen; ++i)
{
switch (sHex[i])
{
case '0': sReturn.append("0000"); break;
case '1': sReturn.append("0001"); break;
case '2': sReturn.append("0010"); break;
case '3': sReturn.append("0011"); break;
case '4': sReturn.append("0100"); break;
case '5': sReturn.append("0101"); break;
case '6': sReturn.append("0110"); break;
case '7': sReturn.append("0111"); break;
case '8': sReturn.append("1000"); break;
case '9': sReturn.append("1001"); break;
case 'a': sReturn.append("1010"); break;
case 'b': sReturn.append("1011"); break;
case 'c': sReturn.append("1100"); break;
case 'd': sReturn.append("1101"); break;
case 'e': sReturn.append("1110"); break;
case 'f': sReturn.append("1111"); break;
}
}

int rLen = sReturn.length();
int i;
for (i = 0; i < rLen; i++)
{
if (sReturn[i] != '0')
{
break;
}
}
sReturn.replace(0, i, "");

return sReturn;
}

// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;

// Inset hex type string -> change to binary string
string hexStr;
cin >> hexStr;

string binaryStr = HexString2BinaryString(hexStr);
//cout << binaryStr << endl;

machineInfo::msgOption option;

{
// ** I want to use 'binaryStr' variable to parse 'option' variable
// can you help me out?

//fstream input("output.bin", ios::in | ios::binary);
//if (!option.ParseFromIstream(&input)) {
// cerr << "Failed to parse address book." << endl;
// return -1;
//}
}
// Optional:  Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();

return 0;
}

I want to parse binary string into message 'option'
Can I make message without using "output.bin" file, by using 'binary string' I made in cpp. 

Josh Haberman

unread,
Jan 8, 2018, 1:02:21 PM1/8/18
to Protocol Buffers
If you have a proper binary buffer, you should be able to pass it to option.ParseFromString(binaryString).

But your HexString2BinaryString() function is not correct. You need to convert each pair of hex digits into a single binary byte. Right now you are converting the hex digits into a human-readable text string of binary digits, which is not what you want.
Reply all
Reply to author
Forward
0 new messages