C ++中的Hex加法

时间:2013-12-11 12:48:27

标签: c++

我想在Hex中添加一个数组。我这样做了,但我在添加功能方面遇到了问题;它不会添加但会显示一些图片。

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;
    }
}

任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:3)

hexDecOnehexDecTwo中存储的“数字”不是十六进制数字,它们是等于'0''1'等的字符,直到'F'为止。您的convert功能也需要将字符'0'转换为'9',之后您需要将结果转换为数字,以便将数字显示为字符。

顺便说一句,当两个hexDec的最高有效数字相加时,你的代码会产生一个缓冲区溢出。

答案 1 :(得分:0)

您需要更改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
}

答案 2 :(得分:0)

我看到了各种各样的方法,到目前为止没有人提到明显的,内置的功能::我已经包含一种stringstream方式来操纵十六进制字符数组并使用std::dec和{ {1}}在十六进制和十进制之间转换。使用下面的代码,我认为您可以轻松地更改代码以合并可用的内置功能。<​​/ p>

我稍微更改了代码以进一步说明用法:

std::hex

当在命令行输入256和ff作为值时,此代码输出以下内容:

#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;
}

这应该允许您轻松地对十六进制值执行数学运算:)

如果您需要更多信息,请与我们联系。:)

答案 3 :(得分:0)

 #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
 }

答案 4 :(得分:0)

以下是“手动”十六进制添加的示例解决方案:

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

答案 5 :(得分:0)

对于大十六进制数,这是一个例子:

.offer-section .divider {
    border: solid 1px #bdbdc3; height: 20px; margin-top: 5%;
}
.offer-section:nth-child(4) .divider{
    border-bottom: none;
}

示例:

#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