1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- //
- // Created by robin on 6/29/15.
- //
-
- #include <sstream>
- #include "ScHex.h"
-
-
- char ScHex::hexCharToInt(const char& c)
- {
- if (c >= 'a')
- return (char)(10 + (c - ('a' - 'A')) - 'A');
- if (c >= 'A')
- return (char)(10 + c - 'A');
- return c - '0';
- }
-
- ScByteArray ScHex::stringToByteArray(const std::string &str)
- {
- std::string hexa;
- for (auto c : str)
- {
- if (isxdigit(c))
- hexa += c;
- }
- if (hexa.size() % 2)
- hexa.insert(0, "0");
- auto data = new BYTE[hexa.size() / 2];
- for (size_t i = 0; i < hexa.size(); i += 2)
- {
- data[i / 2] = (hexCharToInt(hexa[i]) << 4) | hexCharToInt(hexa[i + 1]);
- }
- return ScByteArray(data, hexa.size() / 2);
- }
-
- std::string ScHex::byteArrayToString(const ScByteArray &bytes, const std::string &separator)
- {
- std::string res;
- for (DWORD i = 0; i < bytes.getSize();++i)
- {
- res += intToHexChar(bytes.getData()[i]);
- if (i != bytes.getSize() - 1)
- res += separator;
- }
- return res;
- }
-
- std::string ScHex::intToHexChar(const char &c)
- {
- std::string res;
- for (auto c1 : {(c & 0xf0) >> 4, c & 0x0f})
- {
- if (c1 < 10)
- res += '0' + c1;
- else
- res += 'A' + (c1 - 10);
- }
- return res;
- }
|