ONLY Need Help with part 2.1. I was trying to use a foor loop. Everyone says it
ID: 3541373 • Letter: O
Question
ONLY Need Help with part 2.1. I was trying to use a foor loop. Everyone says it is really simple and that it shouldnt take very long but i am new to shifting and masking in C.
Shifting and Masking First, write a simple C program that defines an integer i and stores different values in each byte (e.g. 0times 12.345678). Then, using only shifts and masks, print the bytes in the integer from least significant to most significant. Note that hte number of bytes in the integer is found by calling sizeof(int), and you can do this easily with a loop, where each iteration of the loop masks off the bottom byte, prints it. and then shifts the remaining integer to the right 8 bits. Pointer Casting One common trick for manipulating memory contents in C is to cast a pointer between different types. For example, a pointer to an integer am be cast to a pointer to an array of characters. This allows memory previously treated as a sequence of one type of bits and bytes to be examined as a different type of bits and bytes. Again define a simple integer i with different values in each byte. Next, assign the address of this integer (&i;) to a pointer to an array of characters (char *a), as such: char *a = (char *)&i; Print the contents of this array from lowest address to highest address, that is starting from a[0] to a[sizeof(int) - 1]; Compile and run your program. Is the machine you're running on big endian or little endian? Note that the effect from using pointers here, treating one memory location as two different types, can be also be achieved using unions:Explanation / Answer
#include <stdio.h>
int main(void) {
//define int i with different values in all bytes
int i = 0x12345678;
//get number of bytes in i
int size = sizeof(int);
//get i byte sized mask
int mask;
mask = (mask<<8) | 0xFF;
//loop , mask , shift and print
printf("Printing bytes from least significant to most significant ");
int k=0,byte;
for(k=0; k<size;k++)
{
//get masked byte
byte = i & mask;
//print masked byte
printf("Byte %d is: %d ",(k+1),byte);
//shift right by 8 bits
i = i>>8;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.