我想打印出内存连续 8 位的 ASCII 值。
任何位的可能值是 0 或 1。您可能至少需要一个字节。
char * bits = (char*) malloc(1);
在堆上分配 1 个字节。更有效和更轻松的事情是在堆栈上创建一个对象,即:
char bits; // a single character, has CHAR_BIT bits
ifstream 明文;
cleartext.open(sometext);
上面没有写任何东西给内存。它尝试以输入模式打开文件。
它有 ascii 字符和常见的 eof 或 \n 或类似的东西,输入只会是一个文本文件,所以我认为它应该只包含 ASCII 字符,如果我错了,请纠正我。
如果您的文件只有 ASCII 数据,您不必担心。您需要做的就是读入文件内容并将其写出。编译器管理数据的存储方式(即为您的字符使用哪种编码以及如何用二进制表示它们,系统的字节序等)。读取/写入文件的最简单方法是:
// include these on as-needed basis
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
using namespace std;
// ...
/* read from standard input and write to standard output */
copy((istream_iterator<char>(cin)), (istream_iterator<char>()),
(ostream_iterator<char>(cout)));
/*-------------------------------------------------------------*/
/* read from standard input and write to text file */
copy(istream_iterator<char>(cin), istream_iterator<char>(),
ostream_iterator<char>(ofstream("output.txt"), "\n") );
/*-------------------------------------------------------------*/
/* read from text file and write to text file */
copy(istream_iterator<char>(ifstream("input.txt")), istream_iterator<char>(),
ostream_iterator<char>(ofstream("output.txt"), "\n") );
/*-------------------------------------------------------------*/
最后剩下的问题是:你想用二进制表示做点什么吗?如果没有,那就算了。否则,再更新一次您的问题。
例如:处理字符数组以使用分组密码对其进行加密
/* a hash calculator */
struct hash_sha1 {
unsigned char operator()(unsigned char x) {
// process
return rc;
}
};
/* store house of characters, could've been a vector as well */
basic_string<unsigned char> line;
/* read from text file and write to a string of unsigned chars */
copy(istream_iterator<unsigned char>(ifstream("input.txt")),
istream_iterator<char>(),
back_inserter(line) );
/* Calculate a SHA-1 hash of the input */
basic_string<unsigned char> hashmsg;
transform(line.begin(), line.end(), back_inserter(hashmsg), hash_sha1());