回覆列表
  • 1 # 小雪020

    #include iostream"

    using namespace std;

    #define MAX 50

    int main()//十六轉二

    {

    int elem2[MAX];

    char elem16[MAX];

    cout << "請輸入十六進位制數,並以‘$’結束:";

    int flag = 1;

    char ch;

    int i = 0;

    while (flag)

    {

    cin >> ch;

    if (ch != "$")

    {

    elem16[i] = ch;

    i++;

    }

    else

    {

    flag = 0;

    }

    }

    int length1 = i;

    int length2 = 0;

    int n = 0;

    int sum = 0;

    for (n = 0; n < length1; n++)//判斷是否是十六進位制數

    {

    int x = (int)elem16[n];

    if ((x >= 48 && x <= 57) || (x >= 65 && x <= 70))

    sum++;

    }

    if (sum == length1)

    {

    int j = 0;

    int number = 0;

    int k = 0;

    int p = 0;

    int m = 0;

    int cout = 3;

    for (j = 0; j < length1; j++)

    {

    m = cout;

    int x = (int)elem16[j];

    if (x >= 48 && x <= 57)

    {

    number = elem16[j] - 48;

    }

    else if (x >= 65 && x <= 70)

    {

    number = elem16[j] - 55;

    }

    if (number != 1)

    {

    do

    {

    elem2[m] = number % 2;

    number = number / 2;

    length2++;

    k++;

    m--;

    } while (number>1);

    if (k == 3)

    {

    elem2[m] = 1;

    length2++;

    m--;

    }

    else

    {

    elem2[m] = 1;

    m--;

    length2++;

    for (p = 0; p < 3-k; p++)

    {

    elem2[m] = 0;

    length2++;

    m--;

    }

    }

    k = 0;

    }

    else

    {

    elem2[m] = 1;

    m--;

    length2++;

    for (p = 0; p < 3; p++)

    {

    elem2[m] = 0;

    length2++;

    m--;

    }

    }

    cout = cout + 4;

    }

    }

    else

    {

    cout << "輸入的不是十六進位制數!";

    }

    cout << "正序輸出:";

    for (i = 0; i < length2; i++)

    cout << elem2[i] << " ";

    cout << endl;

    return 0;

  • 中秋節和大豐收的關聯?
  • 巔峰的李小龍打街鬥戰能否打贏三國時期巔峰狀態的張飛?