[英]Convert read number into unsigned short in C
I'm trying to convert a read number into unsigned short
. 我正在尝试将读取的数字转换为
unsigned short
。
My program saves a specific number in a file. 我的程序在文件中保存了一个特定的数字。 Afterwards I'm trying to read it and to cast it to another type.
之后,我尝试阅读它并将其转换为另一种类型。 Actually the read value is correct but when I cast it, it's a different value.
实际上,读取的值是正确的,但是当我强制转换时,它是一个不同的值。
Here is how I read my file: 这是我读取文件的方式:
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = malloc(length);
if (buffer) {
fread(buffer, 1, length, fp);
}
fclose(fp);
Let's assume that the value is "1337"; 假设值为“ 1337”; Buffer would have the correct value of "1337";
缓冲区的正确值为“ 1337”;
Now here is how i try to convert the value into an unsigned short
: 现在这是我尝试将值转换为
unsigned short
:
unsigned short num = (unsigned short)buffer;
The var num
is now not anymore that same value as buffer
. 现在var
num
不再是与buffer
相同的值。
What am I doing wrong? 我究竟做错了什么?
This has nothing to do with reading from files. 这与从文件读取无关。 You can't just cast a string (actually a pointer to
char
) to a number and expect it to do anything sensible. 您不能只将字符串(实际上是
char
的指针)转换为数字,并期望它做任何有意义的事情。
What you should do instead is to use a conversion function such as strtoul
(declared in <stdlib.h>
) or sscanf
(declared in <stdio.h>
). 相反,您应该使用诸如
strtoul
(在<stdlib.h>
声明)或sscanf
(在<stdio.h>
声明)之类的转换函数。 But make sure to give it a string, ie ensure buffer
is nul-terminated. 但是请确保给它一个字符串,即确保
buffer
是nul终止的。
You can use atoi function to convert buffer to integer. 您可以使用atoi函数将缓冲区转换为整数。 Please see below working code.
请参见下面的工作代码。
int main()
{
FILE *fp = fopen("data.txt", "r");
if(fp == NULL)
exit(0);
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = malloc(length + 1);
if (buffer)
{
fread(buffer, 1, length, fp);
}
//unsigned long num = (unsigned long)atol(buffer);
unsigned short num = (unsigned short)atoi(buffer);
printf("Number = %u\n", num);
fclose(fp);
return 0;
}
If you see theoretical aspect of it, you have two bytes of data, each byte contribute to value depending on byte position. 如果从理论上看,您有两个字节的数据,每个字节的值取决于字节的位置。
Say number is 1337, in hex it is 0x05 0x39. 假设数字为1337,十六进制为0x05 0x39。
So corresponding integer value = (0x05 * 2 ^ 8) + 0x39 = (5 * 256) + 57 = 1337. 因此对应的整数值=(0x05 * 2 ^ 8)+ 0x39 =(5 * 256)+ 57 = 1337。
Hope it helps you. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.