Anon
Anon

Reputation: 27

I am trying to read all 64 bits from a value inside a struct in little endian

I am trying to read a 64 bit value that's been stored inside of struct.value. I would like to print the value in little endian and the full 64 bit value with trailing 0s. Is there anyway to do this with printf?

struct sample{
uint8_t other values;
uint8_t other values;
uint8_t other values;
uint64_t value  //Not the full struct, just sample code
}sample_t

reader(sample_t sample)
{
 sample.value = 0x1234;
 // I would like to print "3412000000000000"
}

NOTE: This is just sample code to get a general idea, not the actual code. I hope this is enough information to convey what I'm looking for. Thank you in advance!

Upvotes: 0

Views: 83

Answers (3)

0xDEADBEEF
0xDEADBEEF

Reputation: 81

printf cannot do that for you. You will have to do it yourself.

#include <stdio.h>
#include <inttypes.h>

uint64_t mirror(uint64_t value) {
    uint64_t temp, mask = 0xFF;
    int i;
    for (i = 0; i < 8; ++i) {
        temp = (temp << 8) | (value & mask) >> 8 * i;
        mask <<= 8;
    }
    return temp;
}

int main() {
    uint64_t value = 0x1234;

    printf("%llx\n", value);             // Outputs 1234
    printf("%016llx\n", mirror(value));  // Outputs 3412000000000000

    return 0;
}

Upvotes: 0

Weather Vane
Weather Vane

Reputation: 34583

Perhaps like this:

#include <stdio.h>
#include <stdint.h> 

int main(void){
    uint64_t n = 0x1234;
    printf("%02X%02X%02X%02X%02X%02X%02X%02X\n", 
            (unsigned)(n & 255), 
            (unsigned)((n >> 8) & 255), 
            (unsigned)((n >> 16) & 255), 
            (unsigned)((n >> 24) & 255), 
            (unsigned)((n >> 32) & 255), 
            (unsigned)((n >> 40) & 255), 
            (unsigned)((n >> 48) & 255), 
            (unsigned)((n >> 56) & 255) );
    return 0;
}

The above is a bit unwieldy but I solved it as a "one-liner". Here is a function implementation.

#include <stdio.h>
#include <stdint.h> 

int rev_print64(uint64_t n)
{
    int i;
    int res;
    for (i = 0; i < 8; i++) {
        res = printf("%02X", (unsigned)(n & 255));
        if(res != 2)
            return res;
        n >>= 8;
    }
    return 16;
}

int main(void){
    rev_print64(0x1234);
    printf("\n");
    return 0;
}

Program output

3412000000000000

Upvotes: 1

nsilent22
nsilent22

Reputation: 2863

One of the possible solutions:

#include <stdio.h>
#include <inttypes.h>

int main(void) {
    uint64_t value, value_to_print;
    uint8_t *ptr_s = (uint8_t *)&value_to_print;
    uint8_t *ptr_e = ptr_s + sizeof(value_to_print) - 1;
    value = 0x1234;

    // swap the bytes. tidbit: no helper variable used!
    value_to_print = value;
    while (ptr_s < ptr_e) {
        *ptr_s ^= *ptr_e;
        *ptr_e ^= *ptr_s;
        *ptr_s ^= *ptr_e;
        ++ptr_s;
        --ptr_e;
    }
    printf("%016"PRIx64"\n", value_to_print);

    return 0;
}

Upvotes: 0

Related Questions