考慮使用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