2013-04-24 63 views
0

我有一个接受来自C++/CLI richtextbox的十六进制值的应用程序。
该字符串来自用户输入。将字符串格式化为十六进制并验证

样本输入和预期输出。

01 02 03 04 05 06 07 08 09 0A //good input 

0102030405060708090A   //bad input but can automatically be converted to good by adding spaces. 

XX ZZ DD AA OO PP II UU HH SS //bad input this is not hex 

01 000 00 00 00 00 00 01 001 0 //bad input hex is only 2 chars 

如何编写函数:
1.检测输入的是否是好还是坏的输入。
2.如果其输入有误,请检查输入有什么不好:不能有空格,不能是十六进制,必须是2字符分割。
3.如果它的空格不是空格,那么只需自动添加空格。

到目前为止,我通过搜索像一个空间做了一个空间检查:

for (int i = 2; i < input.size(); i++) 
{ 
    if(inputpkt[i] == ' ') 
    { 
     cout << "good input" << endl; 
     i = i+2; 
    } 
    else 
    { 
     cout << "bad input. I will format for you" << endl; 
    } 
} 

但它并没有真正按预期工作,因为它返回:

01 000 //bad input 
01 000 00 00 00 00 00 01 001 00 //good input 

更新

1检查输入是否实际为十六进制:

bool ishex(std::string const& s) 
{ 
    return s.find_first_not_of("abcdefABCDEF ", 0) == std::string::npos; 
} 

回答

0

您是使用C++/CLI还是使用普通C++?你已经标记了C++/CLI,但是你使用的是std :: string,而不是.Net System::String

我建议这是一个总体规划:首先,根据任何空格将大字符串拆分为更小的字符串。对于每个单独的字符串,确保它只包含[0-9a-fA-F],并且是两个字符长的倍数。

的实施可以去像这样:

array<Byte>^ ConvertString(String^ input) 
{ 
    List<System::Byte>^ output = gcnew List<System::Byte>(); 

    // Splitting on a null string array makes it split on all whitespace. 
    array<String^>^ words = input->Split(
     (array<String^>)nullptr, 
     StringSplitOptions::RemoveEmptyEntries); 

    for each(String^ word in words) 
    { 
     if(word->Length % 2 == 1) throw gcnew Exception("Invalid input string"); 

     for(int i = 0; i < word->Length; i += 2) 
     { 
      output->Add((Byte)(GetHexValue(word[i]) << 4 + GetHexValue(word[i+1]))); 
     } 
    } 

    return output->ToArray(); 
} 

int GetHexValue(Char c) // Note: Upper case 'C' makes it System::Char 
{ 
    // If not [0-9a-fA-F], throw gcnew Exception("Invalid input string"); 
    // If is [0-9a-fA-F], return integer between 0 and 15. 
} 
相关问题