-2

I am a beginner and I have 1 question like this: example: int a = 10; now I have to write a program to print the value of the 2nd byte. Thank you very much for your help!

  • see https://stackoverflow.com/questions/8680220/how-to-get-the-value-of-individual-bytes-of-a-variable – debanshu das May 15 '21 at 08:08
  • 1
    Does this answer your question? [How to get the value of individual bytes of a variable?](https://stackoverflow.com/questions/8680220/how-to-get-the-value-of-individual-bytes-of-a-variable) – fpiette May 15 '21 at 08:15
  • Welcome to SO! In future, to get better answers to your questions, show some of the code you've tried, show the output you're expecting, and try to state your question as clearly as possible. Posts that appear to simply ask others to solve homework problems don't generally get much love! – Richard Ambler May 15 '21 at 08:57

1 Answers1

1

We could use masking and shifting to get this information. For example, to get the first (least) byte, we could bitwise AND the integer with 0xFF to ignore all the other bits. To get the second byte, we could AND the integer with 0xFF shifted left 8 bits to ignore all the bits that are not in the second byte, and then shift the result back again 8 bits, etc.

Here is something you can play with to see how this works:

#include <iostream>
using namespace std;

int main() {
  const int n = int(sizeof(int));
  int x;

  cout << "Input an integer (negative to quit)." << endl;
  while (1) {
    cout << ": ";
    cin >> x;
    if (x < 0)
      break;
    for (int i = 0; i < n; i++) {
      int shift = 8 * i, mask = 0xFF << shift, byte = (x & mask) >> shift;
      cout << "[" << i << "]: " << dec << byte << " 0x" << hex << byte << endl;
    }
  }

  return 0;
}
Richard Ambler
  • 4,816
  • 2
  • 21
  • 38