将* char或char转换为位

时间:2014-10-20 23:52:40

标签: c memory bitmap

如何将* char或char转换为位? 例如: 这是我的声明

uint64_t blocks[64];
char * word = "hello";

如何在块[0]内以字节存储单词hello? 我试过这个

int e;
int a = strlen(word);
for (e = 0; e < a; e++) {
    blocks[0] |= !!word[e] >> 8;
}

另外,我将如何扭转这一过程?

1 个答案:

答案 0 :(得分:1)

&#34;我想将char中的位复制到uint64_t中。&#34;

尝试使用memcpy

void * memcpy(void * dst, const void * src, size_t n)

e.g。

memcpy(blocks, word, strlen(word));

多个字符串

关于我的解释是关于复制多个字符串的评论:

memcpyn字节从src复制到dst,因此如果我们要连续复制多个字符串,我们需要确保调用{{1}将memcpy设置为我们复制的最后一个字符串的末尾,假设我们要复制&#34; hello&#34;然后&#34;世界&#34;进入src并最终得到代表&#34; helloworld&#34;的字节。

blocks

这应该很容易适应你正在阅读字符串而不是拥有一组字符数组的情况。


重新获取字符串

要获取// if you have a char** words and uint64_t blocks[64]; or similar uint64_t blocks[64]; const char *words[2] = { "hello", "world" }; size_t offset = 0, len; int num_words = sizeof words / sizeof words[0], n; for (n = 0; n < num_words && offset < sizeof blocks; ++n) { len = strlen(words[n]); memcpy(((void *)blocks) + offset, words[n], len); // note the void * cast offset += len; } 并获得包含其中所有字节的blocks,我们需要记住C中的字符串是空终止的,所以如果我们想将结果视为字符串,那么最后需要一个null。完成复制后(上图),您可以使用最后char *来添加此内容。

offset

顺便说一句,我们不必复制数据以将其视为char new_word[100]; memcpy(new_word, blocks, sizeof new_word); new_word[offset] = 0; ;我们可以投...

char *

...但请记住,如果您这样做,修改char * new_word = (char *)blocks; 也会修改new_word