Home > OS >  What cause undefined behavior when converting from unsign int to sign int and print it out
What cause undefined behavior when converting from unsign int to sign int and print it out

Time:12-07

I have the following codes:


#include "stdio.h"
#include "stdint.h"
#include <string>
#include "string.h"
#include<iostream>
using namespace std;

class myMessage
{
public:
    uint8_t latitude[4];                  //Binary
    uint8_t longitude[4];                 //Binary
};



int8_t sentMessage[4]={0,};

int main()
{
    myMessage msg;
    memset(&msg, 0x00, sizeof(msg));

    uint8_t Input_Latitude[4] = {0x4,0x82,0x85,0xf1} ;

    printf("%x ", Input_Latitude[0] );
    printf("%x ", Input_Latitude[1] );
    printf("%x ", Input_Latitude[2] );
    printf("%x \n", Input_Latitude[3] );
    memcpy(&msg.latitude[0], &Input_Latitude, sizeof(uint8_t) * 4);

    printf("%x ", msg.latitude[0] );
    printf("%x ", msg.latitude[1] );
    printf("%x ", msg.latitude[2] );
    printf("%x \n", msg.latitude[3] );

    memcpy(&sentMessage[0], &msg.latitude[0], 4);
    printf("X ", sentMessage[0] );
    printf("X ", sentMessage[1] );

    printf("X ", sentMessage[2] );
    printf("X \n", sentMessage[3] );
}

When I print it out, I have: 4 82 85 f1 ==> original value

4 82 85 f1 ==> copy from unsign int to unsign int

04 FFFFFF82 FFFFFF85 FFFFFFF1 ==> after implicit converting from unsign int to int and printf

Why do we have a bunch of FFFFFFF ????

I understand that there is some implicit conversion from uint8 to int8 when I run

memcpy(&sentMessage[0], &msg.latitude[0], 4);
// sentMessage is int8_t
// msg.latitude[0] is uint8_t

However, I what I don't understand is some extra FFFFF that clearly exceeds the size of each element in array sentMessage[]

CodePudding user response:

While changing the Printf will work it's not the root cause of the issue.

When you define your array

int8_t sentMessage[4]={0,};

You are using type of int8_t instead of uint8_t so printf tries to print an unsigned integer as a signed integer. The reason you see a bunch of F's is the internal storage method, you can see more about this concept here

CodePudding user response:

The program prints out FFFFFF82 with some extra Fs because of printf.

Printf takes %x and assume that I will pass into it value unsigned int which has 8 bytes.

0x82 with int8_t is unsign 8 bits, or 1 byte. Since printf assumes it is unsigned int, 8 bytes, it prints extra FFFFFF82.

To fix it, we can use format specifier %#04hhx.

The answer to this question is same as Why does printf not print out just one byte when printing hex?

printf("%#04hhx ", sentMessage[0] );
  •  Tags:  
  • c
  • Related