2.18.2012

C語言測驗 (3)

7. 寫一個函式可以將以下陣列的值輸出。輸出方式為bit為1時輸出'*',否則輸出空白字元' ',每處理完一個byte輸出換行'\n'。
    static unsigned char font[] = {
        0x38,
        0x6C,
        0xC6,
        0xFE,
        0xC6,
        0xC6,
        0xC6,
        0x00
    };

Answer:
#include <stdio.h>
#include <string.h>

void PRINT_STAR(int);

int main(void)
{
    static unsigned char font[] = {
        0x38,
        0x6C,
        0xC6,
        0xFE,
        0xC6,
        0xC6,
        0xC6,
        0x00
    };
    int nRet = 0;

    for (nRet = 0; nRet < 8; nRet++) {
        PRINT_STAR(font[nRet]);
        printf("\n");
    }

    return 0;
}

void PRINT_STAR(int X)
{
    int nIndex = 8, nArray[8];

    bzero((void *)nArray, sizeof(int) * 8);
    while ( nIndex >= 0 ) {
        nArray[--nIndex] = X % 2;
        X /= 2;
    }

    for (nIndex = 0; nIndex < 8; nIndex++)
        printf("%c", (nArray[nIndex] == 1)? '*': ' ');

    return;
}
10. 寫一支程式能夠做到以下動作:k = rol(0xA3, 2); k = 0x8E

Answer: 先分析一下0xA3和0x8E的關係,
0xA3 ---> 10100011
0x8E ---> 10001110
所以,結論就是rol()這個函式能夠將所傳進去的第一個參數0xA3最左邊2個位元移到最右邊

#include <stdio.h>

int rol(int, int);

int main(void)
{ 
    int j = 0xA3, k = 2;

    printf("rol(0x%X, %d) = 0x%X \n", j, k, rol(j, k));

    return 0;
}

int rol(int a, int b) {

    int x = a >> (8 - b);

    a <<= b;
    a &= 0xFF;

    return (a + x);
}

相關文章:C語言測驗 (1)C語言測驗 (2)

沒有留言:

張貼留言