Hexadecimal Calculator for Addition and Subtraction - c++

I have an issue with my program which is used to calculate addition and subtraction for Hexadecimals. The algorithm of my program is:
Take 2 strings inputted by the user, and "+" or "-" depending on the
operator they chose
Convert the 2 strings into decimals, and add or subtract
If the second number is bigger, use the bigger number to subtract the smaller number, and put a "-" in front of it when returning the result
(1 - 8 should = -7, but instead, I take 8 - 1 = 7, and return "-" and "7" so it gives "-7)
Take the decimal result from the operation and convert back to hexadecimal
Return string of hexadecimal
However, I have run into a issue where my calculations give me wrong answers.
(For e.g FFFFFF + FFFFFFFFFF prints "FFFFFFE" instead of "10000FFFFFE")
What can I do to solve the issue?
I created my own Power function for this program as I need a a number that can go up to 16 Fs for the Hexadecimal string.
Power Function:
unsigned long long int result = 1;
int i;
for (i = 0; i < y; i++)
{
result *= x;
}
return result;
Code:
int i;
int power = FirstHexaNumber.length() - 1;
int power2 = SeconHexaNumber.length() - 1;
int checkLength = FirstHexaNumber.length();
int checkLength2 = SeconHexaNumber.length();
unsigned long long int decimalNumber = 0;
unsigned long long int decimalNumber2 = 0;
unsigned long long int totalDecimal;
int temporary;
string result;
if (Operator == '+') //check if operator is add or minus
{
//Convert Hex to Decimal for first number
for (i = 0; i < checkLength; i++)
{
if (int(FirstHexaNumber[i]) >= 48 && int(FirstHexaNumber[i]) <= 57) { // check if FirstHexaNumber 0 to 9
decimalNumber += ((int(FirstHexaNumber[i])) - 48) * powerFunc(16, power); //formula to convert hexadecimal into decimal, int(FirstHexaNumber[i]) is used to convert hexa into a number
}
else if (int(FirstHexaNumber[i]) >= 65 && int(FirstHexaNumber[i]) <= 70) // check if FirstHexaNumber is A to F
{
decimalNumber += ((int(FirstHexaNumber[i])) - 55)*powerFunc(16, power);
}
else if (int(FirstHexaNumber[i]) >= 97 && int(FirstHexaNumber[i]) <= 102) // check if FirstHexaNumber is a to f
{
int x = powerFunc(16, power);
decimalNumber += ((int(FirstHexaNumber[i])) - 87)* x;
}
power--; //power-- since it starts from "HexaNumber.length - 1". Power should decrease as assignment of power goes down
}
//Convert Hex to Decimal for second number
for (i = 0; i < checkLength2; i++)
{
if (int(SeconHexaNumber[i]) >= 48 && int(SeconHexaNumber[i]) <= 57) {
decimalNumber2 += ((int(SeconHexaNumber[i])) - 48) * powerFunc(16, power2); //formula to convert Hexadecimal to Decimal
}
else if (int(SeconHexaNumber[i]) >= 65 && int(SeconHexaNumber[i]) <= 70)
{
decimalNumber2 += ((int(SeconHexaNumber[i])) - 55)*powerFunc(16, power2); //formula to convert Hexadecimal to Decimal
}
else if (int(SeconHexaNumber[i]) >= 97 && int(SeconHexaNumber[i]) <= 102)
{
unsigned long long int x = powerFunc(16, power2);
decimalNumber2 += ((int(SeconHexaNumber[i])) - 87)*x; //formula to convert Hexadecimal to Decimal
}
power2--;
}
totalDecimal = decimalNumber + decimalNumber2; //Adds the total decimal to convert into hexadecimal
if (totalDecimal == 0)
{
return "0";
}
//Converts Decimal to Hexadecimal
for (i = 0; totalDecimal != 0; i++) //as long as totalDecimal does not hit 0 from being divided by 16, run the loop
{
temporary = totalDecimal % 16; //use temporary as a variable to temporarily hold onto the number remainder of mod 16
if (temporary >= 10) //if temporary >= 10, that means it needs to be converted to alphabet
{
result.insert(0, 1, temporary + 55); //result.insert inserts a string of text into a spot, and pushes everything else backwards.
} //in this case, result.insert assigns "temporary+55" into the spot of characters 0 to 1.
else //else, it means that the decimal will be a number, add 48 to convert to ascii
{
result.insert(0, 1, temporary + 48);
}
totalDecimal = totalDecimal / 16; //divide by 16 to move on to finding the next digit/alphabet
}
return result;
}
else if (Operator == '-') //check if operator is add or minus
{
//Convert Hex to Decimal for first number
for (i = 0; i < checkLength; i++) //as long as the loop does not exceed the length of the hexadecimal, run it
{
if (int(FirstHexaNumber[i]) >= 48 && int(FirstHexaNumber[i]) <= 57) {
decimalNumber += ((int(FirstHexaNumber[i])) - 48) * powerFunc(16, power);
}
else if (int(FirstHexaNumber[i]) >= 65 && int(FirstHexaNumber[i]) <= 70)
{
decimalNumber += ((int(FirstHexaNumber[i])) - 55)*powerFunc(16, power);
}
else if (int(FirstHexaNumber[i]) >= 97 && int(FirstHexaNumber[i]) <= 102)
{
decimalNumber += ((int(FirstHexaNumber[i])) - 87)*powerFunc(16, power);
}
power--;
}
//Convert Hex to Decimal for second number
for (i = 0; i < checkLength2; i++)
{
if (int(SeconHexaNumber[i]) >= 48 && int(SeconHexaNumber[i]) <= 57) {
decimalNumber2 += ((int(SeconHexaNumber[i])) - 48) * powerFunc(16, power2);
}
else if (int(SeconHexaNumber[i]) >= 65 && int(SeconHexaNumber[i]) <= 70)
{
decimalNumber2 += ((int(SeconHexaNumber[i])) - 55)*powerFunc(16, power2);
}
else if (int(SeconHexaNumber[i]) >= 97 && int(SeconHexaNumber[i]) <= 102)
{
decimalNumber2 += ((int(SeconHexaNumber[i])) - 87)*powerFunc(16, power2);
}
power2--;
}
if (decimalNumber >= decimalNumber2)
{
totalDecimal = decimalNumber - decimalNumber2; //subtract bigger number by smaller number.
if (totalDecimal == 0)
{
return "0";
}
for (i = 0; totalDecimal != 0; i++)
{
temporary = totalDecimal % 16;
if (temporary >= 10)
{
result.insert(0, 1, temporary + 55);
}
else
{
result.insert(0, 1, temporary + 48);
}
totalDecimal = totalDecimal / 16;
}
return result;
}
else
{
totalDecimal = decimalNumber2 - decimalNumber; //subtract bigger number by smaller number.
if (totalDecimal == 0)
{
return "0";
}
for (i = 0; totalDecimal != 0; i++)
{
temporary = totalDecimal % 16;
if (temporary >= 10)
{
result.insert(0, 1, temporary + 55);
}
else
{
result.insert(0, 1, temporary + 48);
}
totalDecimal = totalDecimal / 16;
}
return "-" + result;
}
}
return 0;

You can try this snippet:
int a,b;
cout << "\nEnter A in hex: ";
cin >> hex >> a;
cout << "\nEnter B in hex: ";
cin >> hex >> b;
cout << "\n Addition of " << hex << a <<" and "<< hex << b << " is " << hex << a+b;
cout << "\n Substraction of " << hex << a << " and " << hex << b << " is " << hex << a - b;

int x = powerFunc(16, power); should be long long x = powerFunc(16, power);
Don't know full source of the function pow, the return type should be long long too.
Hexadecimal Calculator can be more simple.
#include <sstream>
std::stringstream ss1(s1),ss2(s2);
ss1 >> std::hex >> i1;
ss2 >> std::hex >> s2;
std::cout << std::hex << std::uppercase << i1 + s2 << std::endl;
std::stringstream res;
res << std::hex << std::uppercase << i1 + i2;
return res.str();

Related

Trying to sum two large large numbers and don't get a result¡

I'm new to c++. My teacher left us to do some "tricky" exercises. On this we have to make the sum of two numbers, the trick here is that the maximum value of each int has to be 2 147 483 650 max, so the result would have to be a long long type (I think)
I'm trying to experiment with this and came out with this result:
#include<iostream>
using namespace std;
int main(){
long num_1 = 0;
long num_2 = 0;
cin>>num_1>>num_2;
long long suma = num_1 + num_2;
cout<<"El resultado es "<<suma;
}
The platform says its incorrect, after testing it I realized that when I input 2147483650 + 2147483650 I don't get any result. Why? Am I understanding something wrong?
There are two issues you are running into. This applies to a 32-bit architecture where the range of long is:
-2147483647 to 2147483647
Your input attempt with cin>>num_1>>num_2; fails for values larger than 2147483647 or smaller than -2147483647 -- but you do not catch that because you fail to check the stream state after the attempted input. You would catch the invalid input with:
if (!(std::cin >> num_1 >> num_2)) { /* validate EVERY input */
std::cerr << "error: invalid long input.\n";
return 1;
}
If your the sum of num_1 and num_2 exceeds the range of values that can be stored in a long (4-bytes on most 32-bit architectures) Undefined Behavior results and your program could appear to work normally, crash or anything in between. To ensure there is no overflow in the sum, you must check the result against the limits of the values that can be stored in long.
A simple method is:
/* check for overflow in sum of signed long */
bool safe_sum_long (long& sum, long a, long b)
{
sum = 0;
if (((b > 0) && (a > (std::numeric_limits<long>::max() - b))) ||
((b < 0) && (a < (std::numeric_limits<long>::min() - b)))) {
return false;
}
sum = a + b;
return true;
}
(See: std::numeric_limits for details on use for obtaining limits for all common types)
The function will return false if the value cannot be added safely, or return true filling the reference sum if the value can be added safely.
Putting it altogether, you could do:
#include <iostream>
#include <limits>
/* check for overflow in sum of signed long */
bool safe_sum_long (long& sum, long a, long b)
{
sum = 0;
if (((b > 0) && (a > (std::numeric_limits<long>::max() - b))) ||
((b < 0) && (a < (std::numeric_limits<long>::min() - b)))) {
return false;
}
sum = a + b;
return true;
}
int main (void) {
long num_1 = 0, num_2 = 0, suma = 0;
if (!(std::cin >> num_1 >> num_2)) { /* validate EVERY input */
std::cerr << "error: invalid long input.\n";
return 1;
}
if (safe_sum_long (suma, num_1, num_2)) /* valid sum */
std::cout << "El resultado es " << suma << '\n';
else
std::cerr << "error: overflow occurs in sum.\n";
}
(note: you will want to review Why is “using namespace std;” considered bad practice?)
Example Use/Output
Valid input:
$ ./bin/overflow_long
2147483646
1
El resultado es 2147483647
Valid input but overflow in result:
$ ./bin/overflow_long
2147483647
1
error: overflow occurs in sum.
Invalid input:
$ ./bin/overflow_long
2147483648
error: invalid long input.
While you do not tell us what architecture you are running on, I'm 99% sure you are running in to the limits of long on your system. If you need to work with the the larger number, use a larger type for num_1 and num_2. Either way, you should still check whether the sum can be done without error. Let me know if you have further questions.
You need to change num_1 and num_2 to be long long as well like this:
int main(){
long long num_1 = 0;
long long num_2 = 0;
cin>>num_1;
cin>>num_2;
long long suma = num_1 + num_2;
cout<<"El resultado es "<<suma;
}
#include <cmath>
#include <iostream>
using namespace std;
int main() {
string s1, s2;
int d = 0;
cin >> s1 >> s2;
if (s1.size() == s2.size()) {
int arr[s1.size() + 1];
for (int i = s1.size() - 1; i >= 0; i--) {
if ((s1[i] - '0' + (s2[i] - '0')) % 10 + d > 9) {
arr[i + 1] = ((s1[i] - '0' + (s2[i] - '0')) % 10 + d) % 10;
d = 1;
} else {
arr[i + 1] = (s1[i] - '0' + (s2[i] - '0')) % 10 + d;
d = (s1[i] - '0' + (s2[i] - '0')) / 10;
}
}
arr[0] = d;
if (arr[0] == 0) {
for (int i = 1; i < s1.size() + 1; i++)
cout << arr[i];
} else {
for (int i = 0; i < s1.size() + 1; i++)
cout << arr[i];
}
} else if (s1.size() > s2.size()) {
int arr[s1.size()];
for (int i = s2.size() - 1; i >= 0; i--) {
if ((s1[s1.size() - s2.size() + i] - '0' + (s2[i] - '0')) % 10 + d > 9) {
arr[i + s1.size() - s2.size()] =
((s1[s1.size() - s2.size() + i] - '0' + (s2[i] - '0')) % 10 + d) %
10;
d = 1;
} else {
arr[i + s1.size() - s2.size()] =
(s1[s1.size() - s2.size() + i] - '0' + (s2[i] - '0')) % 10 + d;
d = (s1[s1.size() - s2.size() + i] - '0' + (s2[i] - '0')) / 10;
}
}
if (d == 1) {
for (int i = s1.size() - s2.size() - 1; i >= 0; i--) {
if ((s1[i] - '0') % 10 + d > 9) {
arr[i] = ((s1[i] - '0') % 10 + d) % 10;
d = 1;
} else {
arr[i] = (s1[i] - '0') % 10 + d;
d = (s1[i] - '0') / 10;
}
}
if (d == 1) {
cout << 1;
for (int i = 0; i < s1.size(); i++)
cout << arr[i];
} else {
for (int i = 0; i < s1.size(); i++)
cout << arr[i];
}
} else {
for (int i = 0; i < s1.size() - s2.size() ; i++) cout << s1[i];
for (int i = s1.size() - s2.size(); i < s1.size(); i++) cout << arr[i];
}
} else if (s1.size() < s2.size()) {
int arr[s2.size()];
for (int i = s1.size() - 1; i >= 0; i--) {
if ((s2[s2.size() - s1.size() + i] - '0' + (s1[i] - '0')) % 10 + d > 9) {
arr[i + s2.size() - s1.size()] =
((s2[s2.size() - s1.size() + i] - '0' + (s1[i] - '0')) % 10 + d) %
10;
d = 1;
} else {
arr[i + s2.size() - s1.size()] =
(s2[s2.size() - s1.size() + i] - '0' + (s1[i] - '0')) % 10 + d;
d = (s2[s2.size() - s1.size() + i] - '0' + (s1[i] - '0')) / 10;
}
}
if (d == 1) {
for (int i = s2.size() - s1.size() - 1; i >= 0; i--) {
if ((s2[i] - '0') % 10 + d > 9) {
arr[i] = ((s2[i] - '0') % 10 + d) % 10;
d = 1;
} else {
arr[i] = (s2[i] - '0') % 10 + d;
d = (s2[i] - '0') / 10;
}
}
if (d == 1) {
cout << 1;
for (int i = 0; i < s2.size(); i++)
cout << arr[i];
} else {
for (int i = 0; i < s2.size(); i++)
cout << arr[i];
}
} else {
for (int i = 0; i < s2.size() - s1.size() ; i++) cout << s2[i];
for (int i = s2.size() - s1.size(); i < s2.size(); i++) cout << arr[i];
}
}
return 0;
}

How to cyclically increment and decrement 26 latin characters in a loop

I want to increment or decrement characters, but have them cycle back to a when going beyond z and to z when going before a.
For example incrementing 'w' by 2 gives 'y' and decrementing 'w' by 2 gives 'u'.
Another example decrementing 'w' by 28 gives 'u' and decrementing 'a' by 256 gives 'e'.
I've figure out how to increment: char(int(A[i]+B-97)%26 +97) where B is the shift amount and A[i] is current character.
Don't overcomplicate. Use modulo to keep the increment or decrement amount in a range of 26 characters, then simply do a range check:
char cyclicIncrementDecrement(char ch, int amount)
{
int newValue = int(ch) + (amount % 26);
if (newValue < 'a') newValue += 26;
if (newValue > 'z') newValue -= 26;
return char(newValue);
}
This method of course assumes ch already is in range of 'a' to 'z'. If not, you need to handle that (put it in range or throw an exception or whatever is appropriate for your application).
Running this:
int main()
{
std::cout << cyclicIncrementDecrement('w', -2) << std::endl;
std::cout << cyclicIncrementDecrement('w', 2) << std::endl;
std::cout << cyclicIncrementDecrement('w', -28) << std::endl;
std::cout << cyclicIncrementDecrement('a', -256) << std::endl;
std::cout << cyclicIncrementDecrement('z', -256) << std::endl;
std::cout << cyclicIncrementDecrement('z', -51) << std::endl;
std::cout << cyclicIncrementDecrement('z', -52) << std::endl;
}
gives:
u
y
u
e
d
a
z
Using modular arithmetic, calculate your answer as modulo 26 and then add 'a' (ASCII 97) to your result.
char cyclic_increment(char ch, int n) {
int tmp = ((ch - 97) + n) % 26;
if (tmp < 0 )
tmp += 26;
return (char)(tmp + 97);
}
Alternatively, you could write the above (without an if) as:
char cyclic_increment(char ch, int n) {
return (((ch - 'a') + n) % 26 + 26) % 26 + 'a';
}
This handles both positive and negative offsets:
unsigned char az_cyclic(int in_ch)
{
constexpr int mod = 26; // There are 26 letters in the English alphabet
int offset = (in_ch - 'a') % mod; // (ASCII To zero-based offset) Mod_26 remainder
if (offset < 0) // If negative offset,
offset += mod; // normalize to positive. For example: -1 to 25
return 'a' + offset; // Normalize to ASCII
}
Use-cases:
int main()
{
unsigned char out_ch = '\0';
out_ch = az_cyclic('a' - 1); // 'z'
out_ch = az_cyclic('a' - 1 - 26); // 'z'
out_ch = az_cyclic('a' - 2); // 'y'
out_ch = az_cyclic('a' + 4); // 'e'
out_ch = az_cyclic('a' + 4 + 26); // 'e'
out_ch = az_cyclic('a' + 2); // 'c'
return 0;
}

Htoi incorrect output at 10 digits

When I input
0x123456789
I get incorrect outputs, I can't figure out why. At first I thought it was a max possible int value problem, but I changed my variables to unsigned long and the problem was still there.
#include <iostream>
using namespace std;
long htoi(char s[]);
int main()
{
cout << "Enter Hex \n";
char hexstring[20];
cin >> hexstring;
cout << htoi(hexstring) << "\n";
}
//Converts string to hex
long htoi(char s[])
{
int charsize = 0;
while (s[charsize] != '\0')
{
charsize++;
}
int base = 1;
unsigned long total = 0;
unsigned long multiplier = 1;
for (int i = charsize; i >= 0; i--)
{
if (s[i] == '0' || s[i] == 'x' || s[i] == 'X' || s[i] == '\0')
{
continue;
}
if ( (s[i] >= '0') && (s[i] <= '9') )
{
total = total + ((s[i] - '0') * multiplier);
multiplier = multiplier * 16UL;
continue;
}
if ((s[i] >= 'A') && (s[i] <= 'F'))
{
total = total + ((s[i] - '7') * multiplier); //'7' equals 55 in decimal, while 'A' equals 65
multiplier = multiplier * 16UL;
continue;
}
if ((s[i] >= 'a') && (s[i] <= 'f'))
{
total = total + ((s[i] - 'W') * multiplier); //W equals 87 in decimal, while 'a' equals 97
multiplier = multiplier * 16UL;
continue;
}
}
return total;
}
long probably is 32 bits on your computer as well. Try long long.
You need more than 32 bits to store that number. Your long type could well be as small as 32 bits.
Use a std::uint64_t instead. This is always a 64 bit unsigned type. If your compiler doesn't support that, use a long long. That must be at least 64 bits.
The idea follows the polynomial nature of a number. 123 is the same as
1*102 + 2*101 + 3*100
In other words, I had to multiply the first digit by ten two times. I had to multiply 2 by ten one time. And I multiplied the last digit by one. Again, reading from left to right:
Multiply zero by ten and add the 1 → 0*10+1 = 1.
Multiply that by ten and add the 2 → 1*10+2 = 12.
Multiply that by ten and add the 3 → 12*10+3 = 123.
We will do the same thing:
#include <cctype>
#include <ciso646>
#include <iostream>
using namespace std;
unsigned long long hextodec( const std::string& s )
{
unsigned long long result = 0;
for (char c : s)
{
result *= 16;
if (isdigit( c )) result |= c - '0';
else result |= toupper( c ) - 'A' + 10;
}
return result;
}
int main( int argc, char** argv )
{
cout << hextodec( argv[1] ) << "\n";
}
You may notice that the function is more than three lines. I did that for clarity. C++ idioms can make that loop a single line:
for (char c : s)
result = (result << 4) | (isdigit( c ) ? (c - '0') : (toupper( c ) - 'A' + 10));
You can also do validation if you like. What I have presented is not the only way to do the digit-to-value conversion. There exist other methods that are just as good (and some that are better).
I do hope this helps.
I found out what was happening, when I inputted "1234567890" it would skip over the '0' so I had to modify the code. The other problem was that long was indeed 32-bits, so I changed it to uint64_t as suggested by #Bathsheba. Here's the final working code.
#include <iostream>
using namespace std;
uint64_t htoi(char s[]);
int main()
{
char hexstring[20];
cin >> hexstring;
cout << htoi(hexstring) << "\n";
}
//Converts string to hex
uint64_t htoi(char s[])
{
int charsize = 0;
while (s[charsize] != '\0')
{
charsize++;
}
int base = 1;
uint64_t total = 0;
uint64_t multiplier = 1;
for (int i = charsize; i >= 0; i--)
{
if (s[i] == 'x' || s[i] == 'X' || s[i] == '\0')
{
continue;
}
if ( (s[i] >= '0') && (s[i] <= '9') )
{
total = total + ((uint64_t)(s[i] - '0') * multiplier);
multiplier = multiplier * 16;
continue;
}
if ((s[i] >= 'A') && (s[i] <= 'F'))
{
total = total + ((uint64_t)(s[i] - '7') * multiplier); //'7' equals 55 in decimal, while 'A' equals 65
multiplier = multiplier * 16;
continue;
}
if ((s[i] >= 'a') && (s[i] <= 'f'))
{
total = total + ((uint64_t)(s[i] - 'W') * multiplier); //W equals 87 in decimal, while 'a' equals 97
multiplier = multiplier * 16;
continue;
}
}
return total;
}

Adding two strings arithmetically

I'm trying to implement a function to add two overly large (let's say 1000 digit long) numbers stored in strings. I'm having problems with correct conversions so I can add numbers correctly.
So far, this is what I've done:
string addBegin (string low, string high, int diff)
{
for (int i = 0; i <= diff; i++)
low = "0" + low;
high = "0" + high;
cout << "low: " << low << "\nhigh: " << high << endl;
string result;
int sum, carry = 0;
for (int i = low.length()-1; i >= 0; i--)
{
sum = (int)low[i] + (int)high[i] + carry;
carry = 0;
if (sum > 9)
{
sum -= 10;
carry = 1;
}
result = to_string(sum) + result;
}
return result;
}
string add (string a, string b)
{
int diff = a.length() - b.length();
if (diff <= 0) return addBegin(a, b, abs(diff));
else return addBegin(b, a, diff);
}
int main (void)
{
string x = add("52","205");
cout << "result: " << x << endl;
return 0;
}
Output:
low: 0052
high: 0205 //the first zero is for potential carry
result: 87899293 //wrong, should be 0257
The result here is made of 4 numbers: 87, 89, 92 and 93. That is obviously wrong, I did some unwanted additions with ASCII values. Any ideas how to make this work? Or is there, by any chance, some ridiculously simple way to add two veeeeery long numbers?
sum = (int)low[i] + (int)high[i] + carry;
This adds the values of the character encodings in e.g. ASCII. You want to subtract '0' from the encoding to get the numeric value.
sum = low[i] - '0' + high[i] - '0' + carry;
Do not forget subtracting '0' from low[i] and high[i] when doing the math.
(int)low[i] is 0x30..0x39 for chars '0'..'9'.
A problem is that you use
sum = (int)low[i] + (int)high[i] + carry;
which should be
sum = low[i] - '0' + high[i] - '0' + carry;

CString Hex value conversion to Byte Array

I have been trying to carry out a conversion from CString that contains Hex string to a Byte array and have been
unsuccessful so far. I have looked on forums and none of them seem to help so far. Is there a function with just a few
lines of code to do this conversion?
My code:
BYTE abyData[8]; // BYTE = unsigned char
CString sByte = "0E00000000000400";
Expecting:
abyData[0] = 0x0E;
abyData[6] = 0x04; // etc.
You can simply gobble up two characters at a time:
unsigned int value(char c)
{
if (c >= '0' && c <= '9') { return c - '0'; }
if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }
return -1; // Error!
}
for (unsigned int i = 0; i != 8; ++i)
{
abyData[i] = value(sByte[2 * i]) * 16 + value(sByte[2 * i + 1]);
}
Of course 8 should be the size of your array, and you should ensure that the string is precisely twice as long. A checking version of this would make sure that each character is a valid hex digit and signal some type of error if that isn't the case.
How about something like this:
for (int i = 0; i < sizeof(abyData) && (i * 2) < sByte.GetLength(); i++)
{
char ch1 = sByte[i * 2];
char ch2 = sByte[i * 2 + 1];
int value = 0;
if (std::isdigit(ch1))
value += ch1 - '0';
else
value += (std::tolower(ch1) - 'a') + 10;
// That was the four high bits, so make them that
value <<= 4;
if (std::isdigit(ch2))
value += ch1 - '0';
else
value += (std::tolower(ch1) - 'a') + 10;
abyData[i] = value;
}
Note: The code above is not tested.
You could:
#include <stdint.h>
#include <sstream>
#include <iostream>
int main() {
unsigned char result[8];
std::stringstream ss;
ss << std::hex << "0E00000000000400";
ss >> *( reinterpret_cast<uint64_t *>( result ) );
std::cout << static_cast<int>( result[1] ) << std::endl;
}
however take care of memory management issues!!!
Plus the result is in the reverse order as you would expect, so:
result[0] = 0x00
result[1] = 0x04
...
result[7] = 0x0E