Macro for setting MSB - Intended to work on both Little andBig-endian machines

Discussion in 'C Programming' started by Myth__Buster, Mar 26, 2013.

  1. Myth__Buster

    Myth__Buster Guest

    Hi All,

    Here is my attempt for setting the MSB of an integer depending upon whetherthe underlying machine is Little or Big-endian. Any comments/suggestions/views are appreciated.

    Here I have assumed though I don't store the 1ULL(LL - long long - to force1 to be stored in a multi-byte memory resource(say register) to hold the value 1) in a variable in my program, it will be accessed as a multi-byte value and hence 1 will be stored in the LSB of most-significant-byte of the value stored in a multi-byte memory resource(register) and not in the LSB ofleast-significant-byte of that resource. Please let me know if this is correct.

    Code:

    #include <stdio.h>
    #include <limits.h>

    #define LSET_MSB(x) ((x) = (x) | 1ULL << (sizeof(x) * CHAR_BIT - 1))

    #define BSET_MSB(x) ((x) = (x) | 1ULL << (CHAR_BIT - 1))

    #define LIITE_ENDIAN (1ULL & 1)

    int main(void)
    {
    unsigned long long int x = 1;

    printf("x : %llu\n", x);
    printf("x : %#llx\n", x);

    if ( LIITE_ENDIAN )
    {
    printf("Little\n");
    LSET_MSB(x);
    }
    else
    {
    printf("Big\n");
    BSET_MSB(x);
    }

    printf("x : %llu\n", x);
    printf("x : %#llx\n", x);

    return 0;
    }


    Cheers,
    Raghavan
    Myth__Buster, Mar 26, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Myth__Buster
    Replies:
    8
    Views:
    221
    Correador UK
    Mar 27, 2013
  2. Myth__Buster
    Replies:
    0
    Views:
    156
    Myth__Buster
    Mar 26, 2013
  3. Myth__Buster
    Replies:
    0
    Views:
    159
    Myth__Buster
    Mar 26, 2013
  4. Myth__Buster
    Replies:
    1
    Views:
    161
    Eric Sosman
    Mar 26, 2013
  5. Myth__Buster
    Replies:
    16
    Views:
    366
    glen herrmannsfeldt
    Mar 26, 2013
Loading...

Share This Page