Created
May 30, 2013 12:59
-
-
Save caoxudong/5677639 to your computer and use it in GitHub Desktop.
字符串与数字的转换
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 将16进制字符串转换为对应的字节数组。 | |
* 其中,字符串中每两个字节作为结果数组中的一个字节的内容的16进制表示 | |
* / | |
char peerId[] = {"0fd5081f306494b7b290c2ef9594c56613212b4945d8ece8fcb832ad1d33a169"}; | |
std::string realPeerId; | |
char tempCh = 0; | |
for (char* ch = peerId; *ch != 0; ch += 2) { | |
char c1 = 0; | |
if ((*ch >= 48) && (*ch <= 57)) { //0~9 | |
c1 = *ch - 48; | |
} else if ((*ch >= 65) && (*ch <= 70)){ //A~Z | |
c1 = *ch - 55; | |
} else if ((*ch >= 97) && (*ch <= 102)){ //a~z | |
c1 = *ch - 87; | |
} | |
char c2 = 0; | |
char *ch2 = ch + 1; | |
if ((*ch2 >= 48) && (*ch2 <= 57)) { //0~9 | |
c2 = *ch2 - 48; | |
} else if ((*ch2 >= 65) && (*ch2 <= 70)){ //A~Z | |
c2 = *ch - 55; | |
} else if ((*ch2 >= 97) && (*ch2 <= 102)){ //a~z | |
c2 = *ch2 - 87; | |
} | |
tempCh = c1 * 16 + c2; | |
printf("%c * 16 + %c = %d\n", *ch, *(ch + 1), c1 * 16 + c2); | |
realPeerId.append(&tempCh); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment