Function behave differently with similar input (C++) -


i trying work modbus protocol , right calculating lrc of messages. made function worked no issue whatever putting , noticed id did not worked 1 input , can't find logical explanation on why don't work.

the function :

void lrcstring(std::string example) {  std::stringstream ss; std::string hex =example.substr(1, example.length()-5); std::vector<unsigned char> hexch; unsigned int buffer; int offset = 0; while (offset < hex.length()) {    ss.clear();    ss << std::hex << hex.substr(offset, 2);    ss >> buffer;    hexch.push_back(static_cast<unsigned char>(buffer));    offset += 2; }  unsigned char lrc=0x00; int i; (i=0;i<hexch.size();i++) {     lrc=lrc+hexch[i]; }  lrc = 0xff-lrc; // 1 complement lrc = lrc+1; // 2 complement  //std::string s = std::to_string(lrc);  //int deci = atoi(s.c_str()); int deci = lrc; int reste=deci % 16; std::string temp; int partiehexa=(deci-reste)/16; std::string temp2;  std::cout << "deci : " << deci << std::endl; std::cout << "reste : " << reste << std::endl; std::cout << "partiehexa : " << partiehexa << std::endl;  std::stringstream ss2; ss2 << reste; ss2 >> temp; ss2 << partiehexa; ss2 >> temp2;  if (partiehexa<10) {lrcascii+=temp2;} if (partiehexa==10) {lrcascii+='a';} if (partiehexa==11) {lrcascii+='b';} if (partiehexa==12) {lrcascii+='c';} if (partiehexa==13) {lrcascii+='d';} if (partiehexa==14) {lrcascii+='e';} if (partiehexa==15) {lrcascii+='f';} if (reste<10) {lrcascii+=temp;} if (reste==10) {lrcascii+='a';} if (reste==11) {lrcascii+='b';} if (reste==12) {lrcascii+='c';} if (reste==13) {lrcascii+='d';} if (reste==14) {lrcascii+='e';} if (reste==15) {lrcascii+='f';}  std::cout << "lrc : " << lrcascii << std::endl;  return; } 

examples on input , result when working :

input > ":040100130013??\r\n"

the cout display "lrc : d5"

input > ":0401cd6b05??\r\n"

the cout display "lrc : be"

d5 , right results.

i tried other inputs , had no problem until :

input > ":0403006b0003??\r\n"

the cout display "lrc : b"

input > ":040306022b00000064??\r\n"

the cout display "lrc : 2"

it should 8b , not b , should 62 , not 2.

we can see last part of lrc other part ignored. stranger in case cout of "partiehexa" showing "8" , "6", not int empty. fail understand why happening in case.

to me seems c code. did analyze code. think problem lies calculating

(partiehexa < 10)

the lrcascii gets assigned while looping through "reste" part of code. in "partiehexa" part of code not assigned anything.

suggestion: change code following , code work

if (partiehexa<10)  {      std::stringstream ss3;     ss3 << partiehexa;     ss3 >> temp2;     lrcascii += temp2; } 

best solution rewrite code in proper optimized way.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -