0

I'm supposed to write a code that can deserialize numbers that are received from another device using serial port (RS232) in the form of a QByteArray without using bitwise operators. The QByteArray can contain any length of data from a single item to more than 20 items or even more. Is this possible?

The solution I've come up with so far is:

int numelems = 0;
int exp = 0;
for(int i = tempba.size() - 1 ; i > -1 ; --i) {
    numelems += (unsigned char)tempba.at(i) * pow(256, exp);
    ++exp;
}

where tempba is a QByteArray filled with data read from a serial port. Is this approach correct? where can it be failed? any better way to achieve this?

max
  • 2,627
  • 1
  • 24
  • 44
  • So what is your question? – Dale Wilson Sep 11 '14 at 20:09
  • @DaleWilson descriptin is updated – max Sep 11 '14 at 20:13
  • Questions: Is this correct? Answer: Create a unit test and see if you get the expected results. Question: Where can it fail? Answer: Create a unit test and see if you can break it. Question: Is there a better way to achieve this. Answer: Probably. What criteria are you using to measure better. (speed, code clarity, safety, .... ?) [hint: avoid the pow function for this type of work. `x *= 256` is your friend.] – Dale Wilson Sep 11 '14 at 20:19
  • This code can fail ([integer overflow](http://en.wikipedia.org/wiki/Integer_overflow)) if `tempba` has more than 4 bytes (because int type usually is 32 bits = 4 bytes) – Rimas Sep 11 '14 at 20:22
  • @Rimas yes it does. how can i achieve the desired results? I think dynamic conversion from an arbitrary length `QByteArray` is not possible since we have no containers to hold the large results. – max Sep 11 '14 at 20:40
  • You can use [uint64_t or int64_t integer type](http://en.cppreference.com/w/cpp/types/integer) (8 bytes), use integers array, but it's unclear what is your desired result? What plan you do with these large numbers? – Rimas Sep 11 '14 at 21:00
  • @Rimas the intention is to find a dynamic way that is not constrained by the number of digits to deserialize a number and display it as a decimal number. the only way to display it is using a string but how to obtain the numbers from an arbitrary sized byte array which is safe and won't fail even with ridiculously large byte arrays is what matters and i don't think achieving that level of dynamicity is impossible. – max Sep 11 '14 at 21:16
  • 1
    Then maybe this is answer to your question: [Big numbers library in c++](http://stackoverflow.com/q/12988099/3908097) – Rimas Sep 11 '14 at 21:26
  • @Rimas GMP looks very promising I'll give it a shot thanks for the info. – max Sep 11 '14 at 21:35

0 Answers0