从 C 中的字符串中读取 char 代码的 Array<Uint16Array>
Read Array<Uint16Array> of char code from string in C
我将 JavaScript 字符串写为二进制,将字符串的每个字符转换为 Uint16Array(2bytes),如下所示:
for(let i = 0; i < name.length; i++) {
dv.setUint16(i * 2, name.charCodeAt(i));
}
我检查了文件大小和字节数是正确的,但是当我从 C 中读取一个字符串时,它打印出意外的数字:
27904
28416
25600
25856
29184
28160
24832
29696
28416
29184
读自JavaScript,是这样的,如我所料:
109
111
100
101
114
110
97
116
111
114
这是从文件中读取字符串的C代码:
// Read name
for(int i = 0; i < nameLen; i++) {
short int c;
fread(&c, 2, 1, fp);
printf("%d\n", c);
}
它是 JavaScript 读取字符串的代码:
for(let i = 0; i < nameLen; i++) {
let char = dv.getUint16(i * 2); // Each of character has 2 bytes
console.log(char);
}
另外,当我尝试使用 int 时,它说:
117468416
117468928
117466112
117466368
117469696
117468672
117465344
117470208
117468928
117469696
据我所知,short int 是 2 字节长度,所以理论上看起来没问题,但为什么我得到那么大的数字?
我在我的电脑上试过了,
printf("%d\n", sizeof(short int));
它说 2。
我不擅长C,所以实际上很难找出问题所在。
任何建议将不胜感激。谢谢!
感谢您的评论。我解决了向右移动 8 位的问题,因为 JavaScript 的 DataView 默认将二进制写为 little-endian。
char name[100] = "";
for(int i = 0; i < nameLen; i++) {
short int c;
fread(&c, 2, 1, fp);
c >>= 8;
}
我将 JavaScript 字符串写为二进制,将字符串的每个字符转换为 Uint16Array(2bytes),如下所示:
for(let i = 0; i < name.length; i++) {
dv.setUint16(i * 2, name.charCodeAt(i));
}
我检查了文件大小和字节数是正确的,但是当我从 C 中读取一个字符串时,它打印出意外的数字:
27904
28416
25600
25856
29184
28160
24832
29696
28416
29184
读自JavaScript,是这样的,如我所料:
109
111
100
101
114
110
97
116
111
114
这是从文件中读取字符串的C代码:
// Read name
for(int i = 0; i < nameLen; i++) {
short int c;
fread(&c, 2, 1, fp);
printf("%d\n", c);
}
它是 JavaScript 读取字符串的代码:
for(let i = 0; i < nameLen; i++) {
let char = dv.getUint16(i * 2); // Each of character has 2 bytes
console.log(char);
}
另外,当我尝试使用 int 时,它说:
117468416
117468928
117466112
117466368
117469696
117468672
117465344
117470208
117468928
117469696
据我所知,short int 是 2 字节长度,所以理论上看起来没问题,但为什么我得到那么大的数字?
我在我的电脑上试过了,
printf("%d\n", sizeof(short int));
它说 2。
我不擅长C,所以实际上很难找出问题所在。
任何建议将不胜感激。谢谢!
感谢您的评论。我解决了向右移动 8 位的问题,因为 JavaScript 的 DataView 默认将二进制写为 little-endian。
char name[100] = "";
for(int i = 0; i < nameLen; i++) {
short int c;
fread(&c, 2, 1, fp);
c >>= 8;
}