gpt4 book ai didi

c - 如何将 char 转换为 unsigned int?

转载 作者:行者123 更新时间:2023-11-30 21:27:26 25 4
gpt4 key购买 nike

程序如何运作

./my program 1 10000100 01000000001000001000000
// Reads the argv's
// Converts them into unsigned ints

如何将 char* 转换为 unsigned int?我假设我使用位操作,但我对 char 到 unsigned int 的转换有点迷失。

代码。

struct _float {
unsigned int sign:1, exp:8, frac:23;
};

union _bits32 {
float fval; // Bits as a float
Word xval; // Bits as a word
Float32 bits; // manipulate individual bits
};

union _bits32 getBits(char *sign, char *exp, char *frac);

int main(int argc, char **argv) {
u = getBits(argv[1], argv[2], argv[3]);
return 0;
}

// Here I am converting the char's into unsigned ints
union _bits32 getBits(char *sign, char *exp, char *frac) {
Union32 new;

// convert char *sign into a single bit in new.bits
new.bits.sign = *sign;

// convert char *exp into an 8-bit value in new.bits
new.bits.exp = *exp;

// convert char *frac into a 23-bit value in new.bits
new.bits.frac = *frac;

return new;
}

最佳答案

因此,您需要读取每一位(每位 1 个字符)并将其保存到正确位位置的整数中。下面是一个函数,可以对最多 32 位的任意长度执行此操作。

// Takes in the string with the bits (e.g. "01010100011")
// Returns the integer represented by those bits (leading bits are 0's)
int parseFromBinary(char* bitString) {
int val = 0;
int i = 0;
// While there are more characters
while (bitString[i] != 0) {
// Shift everything left (multiply by 2) to make room for the new bit
val <<= 1;
// Add the new bit (no effect if it is a 0)
val |= bitString[i] - '0';
i++;
}
return val;
}

您可能希望为每个字段调用此函数一次,但实际上没有必要循环遍历 1 个符号位,这可能会让事情变得不那么清晰。

关于c - 如何将 char 转换为 unsigned int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805344/

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