简体   繁体   English

字符到字节签名

[英]Signed char to byte

I have a binary file written in C containing a signed char data type equal to the number 1. I read in the single byte into a byte data type using MappedByteBuffer. 我有一个用C编写的二进制文件,其中包含一个等于数字1的带符号char数据类型。我使用MappedByteBuffer将单个字节读入字节数据类型。 However, when I print it out I get 49. What am I doing wrong? 但是,当我打印出来时,我得到49。我在做什么错?

C: C:

char * buffer = malloc(100);
signed char c;
int temp;
printf("Coordinate System?\n");
scanf("%s",&buffer[0]);
sscanf(&buffer[0],"%d",&temp);
c = temp+'0';
fwrite(&c,1,1,fd);

Java: Java的:

byte b;
b = file.read();
System.out.println(b) ===> prints the number 49.        

I know it is some kind of bit order or something but I am not sure. 我知道这是某种位顺序或某种顺序,但我不确定。

Thanks 谢谢

The issue is with: 问题在于:

sscanf(&buffer[0],"%c",&c);

it says to scan the incoming character as an ascii value. 它说扫描传入的字符作为ascii值。 so you can type 'a', '-', or '1' and the ascii value will be scanned. 因此您可以输入“ a”,“-”或“ 1”,然后将扫描ascii值。

you would need to scan %d instead to get an actual integer. 您需要扫描%d来获取实际的整数。 you would scan into an int variable instead of a char, then do a 0-255 range check to determine if it's viable to store in a single byte. 您将扫描到一个int变量而不是char中,然后进行0-255范围检查以确定是否可以将其存储在单个字节中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM