考虑使用limits.h中也是如此。
我去一个有点过分但也许一些这适合:
编辑:
Ehrmf。也许BITS_ULL的定义更符合你的追求。
I.e.东西方向:
#define BITS_ULL (sizeof(unsigned long long) * CHAR_BIT)
#define BYTE_ULL (sizeof(unsigned long long))
,然后读BYTE_ULL字节,但化妆舒尔检查的读取的字节大小,而不是它是否为-1后者可能是一个粉碎。我有点不确定你在读取位上的“计算”是什么意思。
您可以读取BYTE_ULL字节,并通过缓冲区[0]的地址强制转换为无符号long long,或考虑字节顺序的位移。或以前和字符指针排序字节。
另外请注意,我已经使用len而不是null终止/ C字符串。
哦,这很有趣:) - 我在学习,而这种黑客攻击就是天堂。
]
#include <stdio.h>
#include <limits.h> /* BITS */
#include <ctype.h> /* isprint() */
#define CHUNK_BITS 62
#define CHUNK_CHAR (CHUNK_BITS/CHAR_BIT)
#define HEX_WIDTH 2
/* print len hex values of s, separate every sep byte with space,
* but do not add trailing space. */
void prnt_cshex(const char *s, int len, int sep)
{
const unsigned char *p = (const unsigned char*)s;
int i;
for (i = 1; i <= len; ++p, ++i)
fprintf(stdout,
"%02x"
"%s",
*p,
(i < len && !((i)%sep) ? " " : ""));
}
/* Print len bytes of s, print dot if !isprint() */
void prnt_csbytes(const char *s, int len)
{
int i = 0;
for (i = 0; i < len; ++s, ++i)
fprintf(stdout,
"%c",
(isprint(*s) ? *s : '.'));
}
/* Pass file as first argument, if none, use default "input.txt" */
int main(int argc, char *argv[])
{
const char *fn = "input.txt";
FILE *fh;
char buffer[CHUNK_CHAR];
const char *p = &buffer[0];
size_t k;
if (argc > 1)
fn = argv[1];
if ((fh = fopen(fn, "rb")) == NULL) {
fprintf(stderr, " * Unable to open \"%s\"\n", fn);
goto fail_1;
}
fprintf(stdout,
"Processing \"%s\"\n"
"Chunks of %d bytes of %d bits = %d bits\n",
fn,
CHUNK_CHAR, CHAR_BIT, CHUNK_CHAR * CHAR_BIT);
if (CHUNK_BITS != CHUNK_CHAR * CHAR_BIT) {
fprintf(stdout,
"%d bits chunk requested. Won't fit, trunkated to\n"
"%d * %d = %d\n"
"%d bits short.\n\n",
CHUNK_BITS,
CHUNK_CHAR, CHAR_BIT, CHUNK_BITS/CHAR_BIT * CHAR_BIT,
CHUNK_BITS - CHUNK_CHAR * CHAR_BIT);
}
while ((k = fread(buffer, 1, CHUNK_CHAR, fh)) == CHUNK_CHAR) {
prnt_cshex(p, CHUNK_CHAR, HEX_WIDTH); /* Print as hex */
printf(" ");
prnt_csbytes(p, CHUNK_CHAR); /* Print as text */
putchar('\n');
}
if (!feof(fh)) {
fprintf(stderr, " * Never reached EOF;\n");
goto fail_close;
}
/* If input file does not fit in to CHUNK, report this */
if (k > 0) {
printf("%d byte tail: '", k);
prnt_csbytes(p, k);
printf("'\n");
}
fclose(fh);
return 0;
fail_close:
fclose(fh);
fail_1:
return 1;
}
哇,不知道我怎么忽视的是,我怎么可能去ASCII文本转换为那么相应的十六进制字节? – 2012-03-18 17:48:13
@Hunter:看到我的编辑 – thumbmunkeys 2012-03-18 17:49:36
谢谢,这正是我遇到的事情。 – 2012-03-18 17:52:30