0

So I am given a long int = 0x0123456789ABCDEF (64-bit int) and I am to extract a certain byte. The least significant byte is 0 and most is 7. So if I wanted the 2nd byte, it should return just AB and if I wanted the 5th byte it should be 45.

int n = 2; //byte I am looking for
long int x;
x = 0x0123456789ABCDEF;

printf("%ld\n", x);  //print out initial

n = n * 8;  //changing the number so it can be a multiple of 8bits = byte
x = (x >> n) & 0x0000000000FF ; //bit shifting the number right and masking to get AB


printf("%ld\n", x);  //print out result

Is this the proper way to try and get the result I am looking for? And what would be a good way to implement this so that the code can change with n?

Nukodi
  • 335
  • 1
  • 9
  • 24
  • 1
    what's the output you're getting, when you run the program? – meetaig Sep 05 '16 at 08:13
  • 1
    Yes, bit shift is the appropriate method since those are system-independent. Be aware however, that doing bit-wise operations on signed types is usually nonsense and also dangerous. – Lundin Sep 05 '16 at 08:13
  • `long` is not guaranteed to have 64 bits. If you need a guaranteed bit-width, use Cs fixed-width types (`uint64_t`). And shifting signed integers is problematic and can invoke undefined behaviour, resp. implementation defined. – too honest for this site Sep 05 '16 at 10:27

0 Answers0