-1

I'm converting uint8_t array to char array & then transmit it using gsm module but the problem while converting uint8_t to char its value changes (eg hex value 0455 become 0400 even sometime 00)

I also try to change keil optimization level3 to level2 but facing same problem.

Here is my code

    uint8_t b_id[2]={11, 12};
    char bike_id[2]={0}; 
    ...
    ...
    {
      ...
      ...
      //send id data
      for(i=0; i<2; i++)
      {
            sprintf(bike_id, "%02x", b_id[i]);
            sim808_send_tcp_tx(bike_id, 2);
      } 

    }
  • Is there by any chance another `char b_id[2]` in those `...` at the top of the block? – StoryTeller - Unslander Monica Feb 23 '17 at 10:13
  • Please provide a [mcve]. – kaylum Feb 23 '17 at 10:15
  • While I do wonder what's in those `...` parts (you're sure you don't modify `id` in any way? No buffer overflows?), I'm more curious about what happens *after* the code you show. You should *really* try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). And of course try to find some way to use a debugger so you could step over the code to see what it really does. – Some programmer dude Feb 23 '17 at 10:15
  • I'm not doing any thing before converting b_id but later on transmitting it for(i=0; i<2; i++) { sprintf(bike_id, "%02x", b_id[i]); sim808_send_tcp_tx(bike_id, 2); } – Kapil Singh Rawat Feb 23 '17 at 10:24
  • I have compiled your code lines (using GCC -Wall --pedantic) and I don't find warnings or error in the code line you written. I suggest you to declare `uint8_t b_id[2]` instead of `char b_id[2]` but this doesn't affect the result . Another suggestion might be to write `b_id[1] = (uint8_t) (id & 0xFF)` but even this doesn't affect the result. – Sir Jo Black Feb 23 '17 at 10:27
  • And what is `bike_id`? I assume it's an array of *at least* three characters? – Some programmer dude Feb 23 '17 at 10:31

1 Answers1

1

The problems are these two lines:

char bike_id[2]={0};
...
sprintf(bike_id, "%02x", b_id[i]);

You forget that strings in C are really called null-terminated byte strings. That null-terminated part is important, and it means that a string of two characters actually needs three characters: The two characters of the string, plus the terminator.

In your case since you only have two characters in the array bike_id the sprintf call will write the terminator out of bounds, leading to undefined behavior.

The simple solution? Make bike_id three characters long.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621