字符串到无符号字符

String to unsigned char

本文关键字:字符 无符号 字符串      更新时间:2023-10-16

如何让自己通过cin而不是在程序代码("message","pwd"(中输入数据?

我需要从stringunsigned 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());