gpt4 book ai didi

C:SHA-1 的输出作为小端到 float

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:24 25 4
gpt4 key购买 nike

根据 this documentation ,我的任务是根据字母数字标识符计算颜色值。这个想法是通过 SHA-1 运行标识符字符串,并使用部分结果来计算颜色值。

我在执行以下步骤时遇到问题:

Treat the output as little endian and extract the last-significant 16 bits. (These are the first two bytes of the output, with the second byte being the most significant one.)

这是我目前所拥有的:

double get_CbCr_angle(const char* identifier) {

unsigned char temp[SHA_DIGEST_LENGTH];
char buf[SHA_DIGEST_LENGTH*2];

// initalise with 0s
memset(buf, 0x0, SHA_DIGEST_LENGTH*2);
memset(temp, 0x0, SHA_DIGEST_LENGTH);

// compute hash into temp
SHA1((unsigned char *)identifier, strlen(identifier), temp);

// print from temp into buf and
// interpret as (signed) chars
int i = 0;
for (i=0; i < SHA_DIGEST_LENGTH; i++) {
sprintf( (char*) &(buf[i*2]), "%02x", temp[i]);
}

printf("SHA1 is %s\n", buf);

// make a union type of char and float so we can read a char array
// as float.
union charFloat {
float f;
char s[sizeof(float)];
};

union charFloat foo;

// put first two chars (bytes) into union.
// bracket notation should be fine since both foo and buf are
// char arrays.
foo.s[0] = buf[1];
foo.s[1] = buf[0];

printf("interpreted as chars: %s\n", foo.s);
printf("interpreted as float: %f\n", foo.f); // 0.000000 - why?

}

但我无法通过这种方法获得任何合理的输出。使用更多字节只会给我 float 以及将其解释为 int 时的无意义值。

显然,我不希望有人为我解决这个问题。我非常感谢您提供一些有关查看方向的提示。

非常感谢。

最佳答案

让我们仔细看看这个算法:

  1. Run the input through SHA-1 (RFC 3174 [4]).
  2. Treat the output as little endian and extract the last-significant 16 bits. (These are the first two bytes of the output, with the second byte being the most significant one.)
  3. Divide the value by 65536 (use float division) and multiply it by 2π (two Pi).

该算法并不是说将前两个字节视为浮点值。它说将它们视为 16 位整数,然后将值转换为浮点类型以用于下一步。

此外,在转换值时,您应该使用 temp 而不是 buf,因为 buf 包含表示哈希输出的可打印字符,而 temp 包含实际输出。

所以你会像这样转换值:

uint16_t value;
value = temp[0];
value |= temp[1] << 8;

然后将其转换为 double 以进行下一步:

double result = value * 2 * M_PI / 65536;

关于C:SHA-1 的输出作为小端到 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47740505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com