簡體   English   中英

C ++中的十六進制加法

[英]Hex addition in C++

我想在十六進制中添加一個數組。 我已經做到了,但是我在加法函數中遇到了問題。 它沒有添加,但顯示了一些圖片。

void addition(char hexDecOne[10], char hexDecTwo[10], char (&hexDecSum)[10]) {
    for (int i = 0; i < 10; i++) {
        // convert to decimal and add both array values
        hexDecSum[i] = convert(hexDecOne[i]) + convert(hexDecTwo[i]);
        // add values and if they are greater than F add 1 to next value
        hexDecSum[i + 1] += hexDecSum[i] / 16;
        hexDecSum[i] %= 16;
    }
}

int convert(char item) {
    switch (item) {
        case 'A':
            return 10;
            break;
        case 'B':
            return 11;
            break;
        case 'C':
            return 12;
            break;
        case 'D':
            return 13;
            break;
        case 'E':
            return 14;
            break;
        case 'F':
            return 15;
            break;
    }
}

任何幫助將不勝感激。

存儲在hexDecOnehexDecTwo中的“數字”不是十六進制數字,它們是等於'0''1'等的字符,直到'F'為止。 您的convert函數還需要將字符'0'轉換為'9' ,然后,您需要以另一種方式將結果轉換為數字才能顯示為字符。

順便說一句,當兩個hexDec的最高有效位hexDec表示非空進位時,您的代碼將創建緩沖區溢出。

您需要convert函數更改為處理0 .. 9以及A .. F

unsigned short convert(char item) {
    if (item >= 'A' && item <= 'F') 
        return static_cast<unsigned short>('A' - item + 10);
    else if (item >= '0' && item <= '9')
        return static_cast<unsigned short>('0' - item);
    else // handle error
}

我看到這樣做的,到目前為止,沒有人提到顯而易見的,內置功能的各種方式::我已經包含了一個stringstream操縱十六進制字符數組和使用方式std::decstd::hex為十六進制之間轉換十進制。 使用以下代碼,我認為您可以輕松地更改代碼以合並可用的內置功能。

我對代碼做了一些更改以進一步說明用法:

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    const char* test = "deadbeef"; // or indeed you could pass in any array of char
    unsigned int x;
    std::stringstream ss;          // set up a stringstream object to use for conversions 
    ss << std::hex << test;        // put the value held by test into the stringstream, telling the stringstream its a hex value
    ss >> x;                       // put the value held by the stringstream into x (now a decimal)
    std::cout << "as an unsigned value: "<< x<<std::endl;    // output it as an usigned int
    std::cout << "as a signed value" <<static_cast<int>(x) << std::endl; // output it as signed int
    // now we can use similar functionality with inputs from the user
    int input ;
    std::cout << "Enter decimal number: " ;
    std::cin >> input ;
    std::cout << "0x" << std::hex << input << std::endl ;
    std::string inpStr;
    std::cout << "Please input a hex string without the preceding 0x:";
    std::cin >> inpStr;
    std::stringstream ss2;
    ss2 << std::hex <<inpStr;
    ss2 >> x;
    std::cout << "The value of 0x" <<inpStr<<" in hex is actually: "<< std::dec << x << " in decimal\n";
    // to do additions try the following:
    int firstInt = 0xab;
    int secInt = 0xff;
    std::cout << "the values 0xab + 0xff = 0x" <<std::hex << (firstInt+secInt);
    std::cout << " and in decimal: "<< std::dec << firstInt << "+" << secInt << "= "<< (firstInt+secInt);

    return x;
}

當在命令行中輸入256和ff作為值時,此代碼輸出以下內容:

as an unsigned value: 3735928559
as a signed value-559038737
Enter decimal number: 256
0x100
Please input a hex string without the preceding 0x: ff
The value of 0xff in hex is actually: 255 in decimal
the values 0xab + 0xff = 0x1aa and in decimal: 171+255= 426

那應該使您可以輕松地對十六進制值進行數學運算:)

如果您需要更多信息,請與我們聯系。:)

 #include <iostream>
 #include <string>
 #include <map>
 #include <cctype>
 #include <algorithm>

 using namespace std;

 int convert2i(char item) {
     static bool isFirst = true;
     static map<char, int>lookup;
     if(isFirst){
         for(int i=0;i<16;++i)
             lookup["0123456789ABCDEF"[i]]=i;
         isFirst = false;
     }
     return lookup[::toupper(item)];
 }

 char convert2C(int num){
     static bool isFirst = true;
     static map<int, char>lookup;
     if(isFirst){
         for(int i=0;i<16;++i)
             lookup[i]="0123456789ABCDEF"[i];
         isFirst = false;
     }
     return 0 <= num && num <= 15 ? lookup[num] : -1;
 }

 void addition(char hexDecOne[10], char hexDecTwo[10], char (&hexDecSum)[10]) {
     int carry = 0;
     for (int i = 0; i < 9; i++) {// 9 : 10-1 (-1 for EOS)
         int wk = convert2i(hexDecOne[i]) + convert2i(hexDecTwo[i]) + carry;
         if(wk < 16){
             carry = 0;
         } else {
             carry = 1;
             wk -= 16;
         }
         hexDecSum[i] = convert2C(wk);
     }
     if(carry)
         cerr << "overflow in addition" << endl;
 }

 int main(void){
     char hex1[10] = "ABC000000";
     char hex2[10] = "FED000000";
     char sum[10];

     addition(hex1, hex2, sum);
     reverse(sum, sum+sizeof(sum)-1);//reverse(&sum[0], &sum[9]);//[0,9)
     cout << string(sum) << endl;//000001AA9
 }

這是“手動”十六進制加法的示例解決方案:

char hexOne[8];
char hexTwo[8];
char hexSum[9];

int char2dec(char hex_char)
{
    // assume 0-9A-F input - no error handling

    if ((hex_char >= '0') && (hex_char <= '9'))
    {
        return hex_char - '0';
    }
    else
    {
        return hex_char - 'A' + 10;
    }
}

char dec2char(int dec)
{
    // assume 0-15 input - no error handling
    return "0123456789ABCDEF"[dec];
}

void addHex(char hexOne[8], char hexTwo[8], char hexSum[9])
{
    char carry = '0';
    int i;

    for (i = 0; i < 8; i++)
    {
        char sum = char2dec(hexOne[i]) + char2dec(hexTwo[i]) + char2dec(carry);
        carry = dec2char(sum / 16);
        sum  = sum % 16;

        hexSum[i] = dec2char(sum);
    }

    if (carry != '0') hexSum[i] = carry;
}

void printHexWithoutCarry(char hex[])
{
    char print = 0;
    printf("0x");

    for(int digit = 7; digit >= 0; digit--)
    {
        // skip 0s
        if (digit)
        {
            if ( hex[digit] != '0' ) print = 1;
        } 
        else
        {
            print = 1;
        }

        if (print)
        {
            printf("%c", hex[digit]);
        }
    }
}

void encodeAsHexArray(int val, char dst[])
{
    for(int digit = 0; digit < 8; digit++)
    {
        char tmp = val & 0xF;
        dst[digit] = dec2char(tmp);
        val >>= 4;
    }
}

void main(void)
{
    encodeAsHexArray(0xFF, hexOne);
    encodeAsHexArray(0x1, hexTwo);

    printHexWithoutCarry(hexOne); printf("\n");
    printHexWithoutCarry(hexTwo); printf("\n");
    addHex(hexOne, hexTwo, hexSum);
    printHexWithoutCarry(hexSum);
}

結果:

0xFF
0x1
0x100

對於較大的十六進制數,這是一個示例:

#include <iostream>
#include <string>

using namespace std;

string plus_hex(string hex1, string hex2)
{
    if (hex1.length() < hex2.length())
        hex1.swap(hex2);

    //for convenience, make sure that hex1 is longer.

    /*Strat algorithm*/

    int length1, length2;
    length1 = hex1.length();
    length2 = hex2.length();
    int flag = 0; // carry
    int get1, get2;
    int sum;

    while (length1>0)
    {
        //get first number
        if (hex1[length1 - 1] >= 'A')
            get1 = hex1[length1 - 1] - 55;
        else
            get1 = hex1[length1 - 1] - '0';

        //get second number

        if (length2 > 0)
        {
            if (hex2[length2 - 1] >= 'A')
                get2 = hex2[length2 - 1] - 55;
            else
                get2 = hex2[length2 - 1] - '0';
        }
        else
            get2 = 0;

        //get the sum
        sum = get1 + get2 + flag;

        if (sum >= 16)
        {
            int left = sum % 16;
            if (left >= 10)
                hex1[length1 - 1] = 'A' + left % 10;
            else
                hex1[length1 - 1] = '0' + left;
            flag = 1;
        }
        else
        {
            if (sum >= 10)
                hex1[length1 - 1] = 'A' + sum % 10;
            else
                hex1[length1 - 1] = '0' + sum;
            flag = 0;
        }

        length1--;
        length2--;
    }

    if (flag == 1)
        return "1" + hex1;
    else
        return hex1;

    /*End of algorithm*/
}
int main(void)
{
    string hex1, hex2;

    while (cin >> hex1 >> hex2)
        cout << plus_hex(hex1, hex2);

    return 0;
}

例:

For example:

FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
1

結果:

10000000000000000000000000000000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM