【问题标题】:C++ Using unsigned char instead of typedef unsigned __int8C++ 使用 unsigned char 代替 typedef unsigned __int8
【发布时间】:2013-10-11 15:48:57
【问题描述】:

我正在使用一个我非常喜欢的课程:

#pragma once
#include "StdAfx.h"
#include "xorcipher.h"
#include <vector>

using namespace std;

typedef unsigned __int8 BYTE;

    vector<BYTE>m_Key;

    CXORcipher::CXORcipher()
    {   
        m_Key.push_back(0x55);
        m_Key.push_back(0xae);
        m_Key.push_back(0x8c);
        m_Key.push_back(0x14);
    }
    CXORcipher::~CXORcipher()
    {
    }

    vector<BYTE> xor_encryptdecrypt(const vector<BYTE>&uInput)
    {
        vector<BYTE> ret;
        ret.reserve(uInput.size());

        vector<BYTE>::const_iterator keyIterator = m_Key.begin();

        for(vector<BYTE>::const_iterator inputIterator = uInput.begin(); inputIterator != uInput.end(); ++ inputIterator)
        {
            ret.push_back(*inputIterator ^ *keyIterator);

            // advance the key iterator, wrapping to begin.
            if(++ keyIterator == m_Key.end())
            {
                keyIterator = m_Key.begin();
            }
        }
        return ret;
    }

但是,我想提供一个 unsigned char 向量而不是 typedef。 我对 C++ 还不是很坚定,我害怕把事情搞砸。

有人能告诉我我能做什么吗?

谢谢!

【问题讨论】:

  • 我不明白:vector&lt;BYTE&gt; 已经是 vector&lt;unsigned char&gt;。你能澄清你的问题吗?
  • typedef 是“弱”的。如果您将typedef A 用作B,则可以交替使用AB

标签: c++ class typedef encryption


【解决方案1】:

您可以#include 并使用uint8_t,它是一个8 位无符号整数,通常称为unsigned char

例子:

#include <cstdint>
typedef uint8_t BYTE;

【讨论】:

    【解决方案2】:

    __int8 似乎是 Microsoft 特定的关键字。 (这不是typedef;如果是unsigned __int8 将是语法错误。)

    定义byteBYTE 类型的合理方法是作为unsigned char 的typedef。或者你可以直接使用unsigned char而不使用typedef;任何 C 或 C++ 程序员都会将其识别为大小正好为 1 字节的无符号类型。

    你可以使用uint8_t,定义在&lt;cstdint&gt;如果你愿意假设CHAR_BIT == 8,这是很常见但不是通用的。 (C 和 C++ 中的“字节”是char 的大小,至少8 位,但可以更多。)

    我不知道unsigned charunsigned __int8 是否是同一类型,但我怀疑它们是。无论如何,使用__int8 会使您的代码不可移植。 (如果您不需要将其移植到非 Microsoft 平台上,这不一定是致命缺陷,但与使用 Microsoft 特定 C++ 相比,更多人能够使用标准 C++ 为您提供帮助。)

    Matthias247's answer 的评论中,您写道:

    不幸的是,简单的替换对我不起作用。这 有问题的行是这一行:for(vector<unsigned char>::const_iterator inputIterator = uInput.begin(); inputIterator != uInput.end(); ++ inputIterator) 我没有任何迭代器 unsigned char.

    请更新您的问题,添加显示问题的代码和确切的错误消息。 (不要删除现有代码,因为您已经有引用它的答案。)

    【讨论】:

      【解决方案3】:

      我认为当你传递一个向量时它会马上,因为 BYTE 是通过定义为 __int8 的 typedef,在我看来它与 unsigned char 相同。

      你可以做什么:

      1. 将所有出现的 BYTE 替换为 unsigned char(这对您的代码是安全的)
      2. 创建 CXORcipher 类的模板化版本,它适用于不同的数据类型。

      【讨论】:

      • 不幸的是,简单的替换对我不起作用。有问题的一行是: for(vector::const_iterator inputIterator = uInput.begin(); inputIterator != uInput.end(); ++ inputIterator) 我没有 unsigned char 的任何迭代器。
      • 错误信息是什么?您是否也将 uInput 更改为 const vector& ?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      相关资源
      最近更新 更多