This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

C question regarding printf

int temp 1 , temp2;

         temp1  = ((packet_analyze[i]     << 56)  & 0xFF000000);
         temp1 |= ((packet_analyze[i+1]   << 48)  & 0x00FF0000);
         temp1 |= ((packet_analyze[i+2]   << 40)  & 0x0000FF00);
         temp1 |= ((packet_analyze[i+3]   << 32)  & 0x000000FF);
         temp2  = ((packet_analyze[i+4]   << 56))  & 0xFF000000;
         temp2 |= ((packet_analyze[i+5]   << 48))  & 0x00FF0000;
         temp2 |= ((packet_analyze[i+6]   << 40))  & 0x0000FF00;
         temp2 |= ((packet_analyze[i+7]   << 32))  & 0x000000FF;
          printf("Source address= 0x%0.8x%0.8x\n",temp1,temp2);

Expected output = 0x0af2446a20b23ff5
Output obtained = 0x000000000000000

  • Your shift values vastly exceed the actual width of the int type (16 bits for C51). The values all shift off the end of the type, resulting in zero, before the bitmasks are applied. (And even if they didn't, half the bitmask values are too large.)

    Your printf specifiers are for "ints" (16 bits" and not longs ("%lx").


    Why not go for the much simpler

    for (j = 0; j < 8; ++j)
        printf ("%bx", packet_analyze[i+j]);
    

    Or feel free to unroll that into

    printf ("%bx%bx%bx%bx%bx%bx%bx%bx\n",
        packet_analyze[i],
        packet_analyze[i+1],
        packet_analyze[i+2],
        packet_analyze[i+3],
        packet_analyze[i+4],
        packet_analyze[i+5],
        packet_analyze[i+6],
        packet_analyze[i+7]
        );
    
    

    ANSI C specifies that: - shorts are at least 16 bits - longs are at least 32 bits - an int is at least as long as a short and no longer than a long. It's a coding error to assume that a int is a particular width. You might be willing to live with that if you never port your code -- or if you never port your knowledge of C and coding habits to a different processor. Most people I know have adopted the habit of typedef's a series of specific width integer types, and never using the built in ones. For example:

    typedef U8 unsigned char; // unsigned 8 bit int

    typedef U16 unsigned short; // unsigned 16 bit int

    typedef U32 unsigned long;