I gotta question about Ice in C++. One of my methods requires that I pass in a Ice::ByteSeq. I would like to build this ByteSeq from a string. How is this conversion possible?

I tried the options below.

Ice::ByteSeq("bytes")        // Invalid conversion to unsigned int
Ice::ByteSeq((byte*)"bytes") // Invalid conversion from byte* to unsigned int
(Ice::ByteSeq)"bytes"        // Invalid conversion from const char& to unsigned int
(Ice::ByteSeq)(unsigned int)atoi("bytes") // Blank (obviously, why did I try this?)

How can I make this happen?

EDIT

"bytes" is a placeholder value. My actualy string is non-numeric text information.

有帮助吗?

解决方案

Looking at the header, ByteSeq is an alias for vector<Byte>. You can initialise that from a std::string in the usual way

std::string s = "whatever";
Ice::ByteSeq bs(s.begin(), s.end());

or from a string literal with a bit more flappery, such as

template <size_t N>
Ice::ByteSeq byteseq_from_literal(char (&s)[N]) {
    return Ice::ByteSeq(s, s+N-1); // assuming you don't want to include the terminator
}

Ice::ByteSeq bs = byteseq_from_literal("whatever");

其他提示

You were almost there,

Ice::ByteSeq((unsigned int)atoi("bytes"));

should do it

Assuming your Ice::ByteSeq has a constructor that takes unsigned int

To split this down, it's basically doing

int num = atoi("12345"); // num = (int) 12345 
unsigned int num2 = (unsigned int)num;  // num2 = (unsigned int) 12345
Ice::ByteSeq(num2);

If Ice::ByteSeq is simply a vector of bytes you can convert a string to a vector of bytes by doing a variation of the following:

std::string str = "Hello World";
std::vector<char> bytes(str.begin(), str.end());

The implementation of Ice::Byte is an unsigned char just change the standard code I posted from:

std::vector<char> bytes(str.begin(), str.end());

to

std::vector<unsigned char> bytes(str.begin(), str.end());

and the generated vector should be directly compatible with an Ice::ByteSeq

sample code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    std::string str = "Hello World";
    std::vector<unsigned char> bytes(str.begin(), str.end());
    cout << str << endl; 

    for(int i=0; i < bytes.size(); i++)
        std::cout << bytes[i] << '\n';
   return 0;
}

Hope this helps:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top