字符串到无符号字符
String to unsigned char
如何让自己通过cin
而不是在程序代码("message
","pwd
"(中输入数据?
我需要从string
到unsigned char
进行转变,但我不知道如何。代码本身是实现 RC4 的尝试
#include <iostream>
#include <string.h>
using namespace std;
void rc4(unsigned char * ByteInput, unsigned char * pwd,
unsigned char * &ByteOutput){
unsigned char * temp;
int i,j=0,t,tmp,tmp2,s[256], k[256];
for (tmp=0;tmp<256;tmp++){
s[tmp]=tmp;
k[tmp]=pwd[(tmp % strlen((char *)pwd))];
}
for (i=0;i<256;i++){
j = (j + s[i] + k[i]) % 256;
tmp=s[i];
s[i]=s[j];
s[j]=tmp;
}
temp = new unsigned char [ (int)strlen((char *)ByteInput) + 1 ] ;
i=j=0;
for (tmp=0;tmp<(int)strlen((char *)ByteInput);tmp++){
i = (i + 1) % 256;
j = (j + s[i]) % 256;
tmp2=s[i];
s[i]=s[j];
s[j]=tmp2;
t = (s[i] + s[j]) % 256;
if (s[t]==ByteInput[tmp])
temp[tmp]=ByteInput[tmp];
else
temp[tmp]=s[t]^ByteInput[tmp];
}
temp[tmp]=' ';
ByteOutput=temp;
}
int main()
{
unsigned char * message;
unsigned char * pwd;
unsigned char * encrypted;
unsigned char * decrypted;
message=(unsigned char *)"Hello world!";
pwd=(unsigned char *)"abc";
rc4(message,pwd,encrypted);
rc4(encrypted,pwd,decrypted);
cout<<"Test"<<endl<<endl;
cout<<"Message: "<<message<<endl;
cout<<"Password: "<<pwd<<endl;
cout<<"Message encrypted: "<<encrypted<<endl;
cout<<"Message decrypted: "<<decrypted<<endl;
return 0;
}
std::string
有一个.c_str()
成员函数,该函数将const char *
返回给内部字符串。您可以使用reinterpret_cast
将其转换为const unsigned char*
。例:
#include <string> // string not string.h
std::string message;
std::getline (std::cin, message);
const unsigned char* msg = reinterpret_cast<const unsigned char*>(message.c_str());
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 库特无符号字符
- 寻找一种更好的方法来表示无符号字符数组
- C++ 无符号字符 *{varName};-> C#
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 将浮点数转换为无符号字符数组并打印出来
- 在函数中返回无符号字符数组,但不返回指针
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 无符号字符打印其 ASCII 值
- 字符数组到无符号字符 *
- 是否可以在 c++ 中将两位数保存在无符号字符中