2014-02-22 116 views
2

我正在写一个算法来解码base64。在靠近尽头下面的代码,如果我改变:奇怪的行为与子字符串

Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0); 

Binary.substr((I - 1) >= 0 ? (I - 1) : 0); 

它抛出std::out_of_range。不过,如果我不管它,它工作正常..

整个代码如下:

#include <iostream> 
#include <bitset> 
#include <algorithm> 

static const std::string Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

std::string DecodeBase64(std::string Data) 
{ 
    std::string Binary = std::string(); 
    std::string Result = std::string(); 

    for (std::size_t I = Data.size(); I > 0; --I) 
    { 
     if (Data[I - 1] != '=') 
     { 
      std::string Characters = Data.substr(0, I); 
      for (auto it = Characters.begin(); it != Characters.end(); ++it) 
       Binary += std::bitset<6>(Base64Chars.find(*it)).to_string(); 
      break; 
     } 
    } 

    for (std::size_t I = 0; I < Binary.size(); I += 8) 
    { 
     int FirstChar = I; 
     std::string str = Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0); 
     Result += static_cast<char>(std::bitset<8>(str).to_ulong()); 
     if (I == 0) ++I; 
    } 

    return Result; 
} 

int main() 
{ 
    std::cout<<DecodeBase64("aGVsbG8gdGhlcmUgbm9vYg=="); 
} 

这是奇怪,因为我分配给IFirstChar之前,我称之为substr所以它应该是同样的确切值..任何想法,为什么发生这种情况?

回答

6

这是因为I的类型是std::size_t,它是无符号的。当I为零时,​​被解释为非常大的正数。

转换Iint恰好在分配解决了这个问题,因为FirstChar现在签署,所以FirstChar -1可能成为负值。

转换I-1 >= 0为等效I >= 1应该可以解决这个问题:

Binary.substr(I >= 1 ? (I - 1) : 0); 
+0

OMG ..签署对无符号=(谢谢你这的确修复它我现在得更加小心 – Brandon

+2

!。 @CantChooseUsernames Double facepalms是有史以来最好的学习时刻;)... –