Friday 19 August 2016

Anirudh

Write a program to get the nth byte of an integer

Problem statement: Given an integer, write a program to extract the nth byte from it.

Example: Let's take an integer in hexadecimal format, say 0x5510EF3A (a 32-bit integer). It has four bytes, given in hexadecimal as:
     Byte 0: 0x3A
     Byte 1: 0xEF
     Byte 2: 0x10
     Byte 3: 0x55
So, if we want to get byte #2, the result would be 0x10.

Solution: We can move the required byte to the rightmost position by right-shifting the number by (8 * required byte number). Now we only need the rightmost byte in our result (the last 8 bits), so we can mask it by doing bitwise AND with 0x000000FF, which is also written as just 0xFF, or 255 in decimal.

#include <stdio.h>

int getByte(int num, unsigned byteno)
{
    return (num >> (byteno * 8)) & 0xFF;    // Mask and return the required byte
}

int main()
{
    int num;
    unsigned byteno;

    printf("\nEnter a hex number: ");
    scanf("%x", &num);        // To take input number in hex, by using %x
    printf("\nEnter byte no to get (0 - 3): ");
    scanf("%u", &byteno);     // To take byte no in unsigned decimal, by using %u

    printf("\nByte no %u in hex representation: %x\n", byteno, getByte(num, byteno));

    return 0;
}

Anirudh

About the author →

Anirudh Khanna is a Computer Science student and a geek who firmly believes in the awesomeness of technology! He is a programmer and web designer, also keenly interested in the research of new and innovative ideas in Computer Science.

Subscribe to Geek Factorial via email :