2010-08-03 155 views
0

我需要將像「... hello2」這樣的ASCII字符串轉換爲十進制和/或十六進制表示形式(數字形式,具體種類無關緊要)。所以,「你好」將是:68 65 6c 6c 6f 32在HEX。如何在不使用巨大if語句的情況下在C++中執行此操作?將ASCII字符串轉換爲十進制和十六進制表示形式

編輯:好了,所以這是我去的解決方案:

int main() 
{ 
    string c = "B"; 
    char *cs = new char[c.size() + 1]; 
    std::strcpy (cs, c.c_str()); 
    cout << cs << endl; 

    char a = *cs; 
    int as = a; 
    cout << as << endl; 
    return 0; 
} 
+0

你可以通過做'char a ='B'來隱式地將任何char轉換爲ascii值。 int as = a;'< - 產生66(ascii值) – 2010-08-03 20:00:35

+0

我喜歡這個技巧。我現在唯一的問題是,如何以這種方式轉換字符串?我想這個問題真的是,我如何將一個字符串的單個元素等同於「a」? – 2010-08-03 20:56:04

+0

你可以在for循環中逐個字符地完成它。 – 2010-08-04 00:15:54

回答

1

您可以用printf()寫結果到標準輸出或者你可以用sprintf/snprintf的寫結果的字符串。這裏的關鍵是格式字符串中的%X。

#include <cstdio> 
#include <cstring> 
int main(int argc, char **argv) 
{ 
    char *string = "hello2"; 
    int i; 

    for (i = 0; i < strlen(string); i++) 
     printf("%X", string[i]); 

    return 0; 
} 

如果處理的一個C++的std :: string,你可以使用string的c_str()方法來產生一個C字符數組。

+0

爲什麼downvote?它工作正常,不是嗎? – brennie 2010-08-03 20:03:25

+0

缺少字符串到ASCII值示例 – 2010-08-03 20:04:15

+0

字符串到ASCII值的示例?海報表明他以ASCII值開頭。 「我需要將ASCII字符串轉換爲...」hello2「」 – brennie 2010-08-03 20:12:34

3

的字符串只是char秒的陣列,因此,所有你需要做的是循環從0strlen(str)-1,並使用printf()或類似於將每個字符格式化爲十進制/十六進制的東西。

+0

這就是C,哥們。 – Puppy 2010-08-03 19:47:51

+2

所以它值得downvote ?? – 2010-08-03 19:49:13

+3

@DeadMG:C仍然有效C++ – 2010-08-03 19:49:35

6

剛打印出來的十六進制,像:

for (int i=0; i<your_string.size(); i++) 
    std::cout << std::hex << (unsigned int)your_string[i] << " "; 

機會是你要設置的精確度和寬度總是給2位等,但總的想法是一樣的。就個人而言,如果我這樣做,我可能會使用printf("%.2x");,因爲它確實正確,而且麻煩少得多。

+0

缺少ASCII值示例 – 2010-08-03 19:58:00

+0

@ 0A0D:缺少合理的downvote藉口。這個問題已經給出了輸入和輸出的例子。我只是告訴他如何得到它。 – 2010-08-03 20:08:55

+0

「hello2」變成了十進制和/或十六進制表示形式「 - 對我來說似乎很清楚他想要十進制和十六進制 – 2010-08-03 20:14:50

0
for(int i = 0; i < string.size(); i++) { 
    std::cout << std::hex << (unsigned int)string[i]; 
} 
+0

在我的編譯器上不起作用(我認爲這是需要的,但我想知道爲什麼) – KeatsPeeks 2010-08-03 19:52:43

+0

什麼是錯誤?編譯器 - 儘管需要強制轉換爲十六進制。 – Puppy 2010-08-03 19:58:10

+0

因爲'operator <<'被重載,並且你需要一個帶'int'(或'short','long'等等的重載)爲'hex'標誌有效(即'char'的重載忽略'hex'標誌)。 – 2010-08-03 19:58:14

1
#include <algorithm> 
#include <iomanip> 
#include <iostream> 
#include <iterator> 

int main() { 
    std::string hello = "Hello, world!"; 

    std::cout << std::hex << std::setw(2) << std::setfill('0'); 
    std::copy(hello.begin(), 
      hello.end (), 
      std::ostream_iterator<unsigned>(std::cout, " ")); 
    std::cout << std::endl; 
} 
相關問題