gpt4 book ai didi

c# - 将 char 转换为 unsigned short : what happens behind the scenes?

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

给定这个字段:

char lookup_ext[8192] = {0}; // Gets filled later

还有这个声明:

unsigned short *slt = (unsigned short*) lookup_ext;

幕后发生了什么?

lookup_ext[1669] 返回 67 = 0100 0011 (C),lookup_ext[1670] 返回 78 = 0100 1110 (N),lookup_ext[1671] 返回 68 = 0100 0100 (D);然而 slt[1670] 返回 18273 = 0100 0111 0110 0001。

我正在尝试将它移植到 C#,所以除了一个简单的方法之外,我还想知道这里到底发生了什么。自从我经常使用 C++ 以来已经有一段时间了。

谢谢!

最佳答案

您显示的语句不会将 char 转换为 unsigned short,它会将 pointer 转换为 char 到 pointer unsigned short。这意味着指向数据的通常算术转换不会发生,并且当通过 slt 变量访问时,底层 char 数据将仅被解释为无符号短整型。

请注意 sizeof(unsigned short) 不太可能是一个,因此 slt[1670] 不一定对应于 lookup_ext[1670]。它更有可能 - 例如,如果 sizeof(unsigned short) 是两个 - 对应于 lookup_ext[3340]lookup_ext[3341] .

你知道为什么原始代码使用这个别名吗?如果没有必要,可能值得尝试使 C++ 代码更简洁,并在移植之前验证行为是否未改变。

关于c# - 将 char 转换为 unsigned short : what happens behind the scenes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/402616/

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