简体   繁体   English

如何转换矢量<int>到一个字符数组?</int>

[英]How to convert vector<int> to a char array?

Platform is Windows with MSVC.平台是带有 MSVC 的 Windows。 I'm writing an encryption unpadding function.我正在写一个加密 unpadding function。

I have many vector<int> which are the results of a decryption function.我有很多vector<int>是解密 function 的结果。 A vector<int> might contain a UTF-8 string, or it might be garbage if the decryption parameters were wrong. vector<int>可能包含 UTF-8 字符串,或者如果解密参数错误,它可能是垃圾。 I need to subtract a number from each position, and then see if it's a valid UTF-8 string.我需要从每个 position 中减去一个数字,然后查看它是否是有效的 UTF-8 字符串。 That's the padding scheme : add a character's position to itself before encrypting.这就是填充方案:在加密之前将字符的 position 添加到自身。

To display the results, I assume I need to convert the vector<int> to a vector<char> .为了显示结果,我假设我需要将vector<int>转换为vector<char> I can then use that as a const char[] and print it to the console.然后我可以将其用作const char[]并将其打印到控制台。

How do I handle the possibility of overflow and underflow when casting to a char ?转换为char时如何处理溢出和下溢的可能性? After all, a char is signed and has a range of -128 to 127 on my platform.毕竟,在我的平台上,一个char已签名并且范围为 -128 到 127。

std::vector<char> unpad(const std::vector<int>& input) {
    std::vector<char> output;
    for (int i{ 0 }; i < input.size(); ++i) {
        if (input[i] < -128 || input[i] > 127) {
            printf("oops overflow\n");
        }
        output.push_back(static_cast<char>(input[i] - i)); // Padding scheme
    }
    output.push_back(static_cast<char>(0)); // Null termination
    return output;
}

I think you're looking at this problem wrong.我认为你看错了这个问题。 You don't want to cast from int to char since you'll lose information.您不想从 int 转换为 char ,因为您会丢失信息。 You want to preserve the information in the int.您想保留 int 中的信息。 What you need to realise is that an int is 32 bits and char 8 bits.您需要意识到的是 int 是 32 位,char 是 8 位。 Therefore you need 4 chars to hold all the information from a single int.因此,您需要 4 个字符来保存来自单个 int 的所有信息。 To extract the information from a single int you need to use bit operators要从单个 int 中提取信息,您需要使用位运算符

char a = some_int & 0x000000ff;
char b = some_int & 0x0000ff00;
char c = some_int & 0x00ff0000;
char d = some_int & 0xff000000;

Now you'll have the 4 bytes (the chars) that map to the parts in a single int.现在您将拥有 map 到单个 int 中的部件的 4 个字节(字符)。 You can work from there to decode utf-8.您可以从那里开始解码 utf-8。

Note that on 64 and 32 bit systems ints take 4 bytes.请注意,在 64 位和 32 位系统上,整数占用 4 个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM