C ++ 16 진 문자열을 부호있는 정수로 변환
C ++에서 16 진수 문자열을 부호있는 32 비트 정수로 변환하고 싶습니다.
예를 들어 16 진 문자열 "fffefffe"가 있습니다. 이진 표현은 11111111111111101111111111111110입니다. 서명 된 정수 표현은 -65538입니다.
C ++에서이 변환을 어떻게 수행합니까? 음수가 아닌 숫자에 대해서도 작동해야합니다. 예를 들어, 16 진수 문자열 "0000000A"는 2 진수로 00000000000000000000000000001010이고 10 진수로 10입니다.
사용하다 std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
다음 예제는 -65538
결과로 생성 됩니다.
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
새로운 C ++ 11 표준에는 사용할 수있는 몇 가지 새로운 유틸리티 기능이 있습니다! 특히 "문자열 대 숫자"기능 군 ( http://en.cppreference.com/w/cpp/string/basic_string/stol 및 http://en.cppreference.com/w/cpp/string/ basic_string / stoul ). 이들은 본질적으로 C의 문자열 대 숫자 변환 함수 주위의 얇은 래퍼이지만std::string
따라서 최신 코드에 대한 가장 간단한 답변은 다음과 같습니다.
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
참고 : 아래는 원래 답변입니다. 편집 한 내용은 완전한 답변이 아닙니다. 기능 솔루션의 경우 코드를 :-) 줄 위에 붙여 넣으십시오.
이후 lexical_cast<>
스트림 변환 의미론을 갖도록 정의 된 것으로 보인다 . 슬프게도 스트림은 "0x"표기법을 이해하지 못합니다. 그래서 boost::lexical_cast
내 손으로 굴린 사람은 16 진수 줄을 잘 다루지 못합니다. 입력 스트림을 수동으로 16 진수로 설정하는 위의 솔루션은 잘 처리합니다.
Boost는이 작업 을 수행 할 수있는 몇 가지 사항 이 있으며 오류 검사 기능도 있습니다. 다음과 같이 사용할 수 있습니다.
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
부스트를 사용하고 싶지 않다면 오류 검사가없는 가벼운 어휘 캐스트 버전이 있습니다.
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
다음과 같이 사용할 수 있습니다.
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
C 및 C ++ 모두에서 작동하는 메소드의 경우 표준 라이브러리 함수 strtol () 사용을 고려할 수 있습니다.
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Andy Buchanan은 C ++을 고수하는 한 당신을 좋아하지만 몇 가지 개조가 있습니다.
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
같은
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
That way you don't need one impl per int type.
Working example with strtoul
will be:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol
converts string
to long
. On my computer numeric_limits<long>::max()
gives 0x7fffffff
. Obviously that 0xfffefffe
is greater than 0x7fffffff
. So strtol
returns MAX_LONG
instead of wanted value. strtoul
converts string
to unsigned long
that's why no overflow in this case.
Ok, strtol
is considering input string not as 32-bit signed integer before convertation. Funny sample with strtol
:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
The code above prints -65538
in console.
Here's a simple and working method I found elsewhere:
string hexString = "7FF";
int hexNumber;
sscanf(hexString.c_str(), "%x", &hexNumber);
Please note that you might prefer using unsigned long integer/long integer, to receive the value. Another note, the c_str() function just converts the std::string to const char* .
So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:
const char *hexString = "7FFEA5"; //Just to show the conversion of a bigger hex number
unsigned long hexNumber; //In case your hex number is going to be sufficiently big.
sscanf(hexString, "%x", &hexNumber);
This works just perfectly fine (provided you use appropriate data types per your need).
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers, A.
This worked for me:
string string_test = "80123456";
unsigned long x;
signed long val;
std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val; // if I try this val = 0
val = (signed long)x; // However, if I cast the unsigned result I get val = 0x80123456
another method
using namespace System;
template <typename NUM>
NUM hexstr2num(String^ h)
{
NUM v=0;
String^ k=L"0123456789ABCDEF";
short l=h->Length;
char off;
h=h->ToUpper();
if(h->Substring(0,1)!=L"H")
{if(h->Substring(0,2)==L"0X") off=2;}
else
{off=1;}
if(!off) throw;
char dx=0;
for(int i=l;i>off;i--)
{
if((dx=k->IndexOf(h->Substring(i-1,1)))>=0)
{v+=dx<<((l-i)<<2);}
else
{throw;}
}
return v;
}
참고URL : https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer
'programing tip' 카테고리의 다른 글
왜 자동 a = 1입니까? (0) | 2020.07.08 |
---|---|
Capistrano-이전 릴리즈 정리 (0) | 2020.07.08 |
Android UI에서 둥근 사각형을 그리는 방법은 무엇입니까? (0) | 2020.07.08 |
명령 행을 통해 Android Studio 앱 빌드 (0) | 2020.07.07 |
파이썬에서 나열하는 사전 키 값에 대한 반복 (0) | 2020.07.07 |