2

基本的に、4バイトが続く文字列のサイズを指定するバイナリ形式を読んでいます。したがって、バッファから読み取っている4文字を1つの整数にキャストしたいと考えています。

これが私が持っているものです。

int FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
  //skip the marker and read next 4 byes
  int cursor = cursor + 4; //skip marker and read 4
  char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};
  int32_t objSize = tmpbuffer;
  return objSize;

}

考え?

4

5 に答える 5

5

手動で解凍するのはとても簡単です:

unsigned char *ptr = (unsigned char *)(buffer + cursor);
// unpack big-endian order
int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
于 2012-10-07T02:06:21.060 に答える
4

これらが格納されている MSB (つまり、ビッグ エンディアン) であると仮定します。

unsigned char *p = (unsigned char*)buffer + cursor;
uint32_t uiSize = (unsigned int)*p <<24 |
                  (unsigned int)*(p+1) << 16 |
                  (unsigned int)*(p+2) << 8 |
                  (unsigned int)*(p+3);

アセンブリに結果を signed int にキャストします。恐ろしいことはわかっていますが、私のタイピングスキルもそうです。

注: 正直なところ、暗黙のアップキャストが符号を char から int に拡張するかどうかは思い出せませんが、拡張する場合は、ここで or で結合された単一バイトのいずれかがトップビット点灯されます。 *p がなかったとしたら、驚くかもしれません。したがって、一見妄想的な unsigned cast-o-festival と、完全に組み立てられた後にのみ signed-int にキャストするフォローアップ。

于 2012-10-07T02:05:35.660 に答える
2

これでうまくいくはずです:

objSize = 0;
for (int i = 0; i < 4; ++ i)
    objeSize += ((int)tmpbuffer[i]) << (8 * i);

また

objSize = 0;
for (int i = 0; i < 4; ++ i)
    objeSize += ((int)tmpbuffer[i]) << (8 * (3 - i));

nneonneo が指摘したビッグエンディアンの場合

于 2012-10-07T01:56:58.500 に答える
-1

関数を使用してntohl、ネットワークからホストのバイトオーダーに変換できます。車輪を再発明する必要はありません。これにはある程度の移植性があるという利点もあり、正しいヘッダーが使用されている限り、ビッグ エンディアンおよびリトル エンディアンの OS で動作します。以下は Windows の例ですが、この機能は Linux でも利用できます。

#include <winsock.h>
#include <iostream>

int main()
{
    char buffer[] = "MARK\x00\x00\x00\x08";
    // Point to the 4-byte network (big-endian) order value.
    unsigned long * size = (unsigned long *)(buffer + 4);
    // Dereference and convert it.
    std::cout << ntohl(*size) << std::endl;
    return 0;
}

出力:

8
于 2012-10-07T05:19:40.047 に答える
-1

あなたが持っているものはうまくいくはずですが、これを置き換えてください

int32_t objSize = tmpbuffer;

このため

int32_t objSize = *((int32_t*)tmpbuffer);
  • 同じアーキテクチャで保存および読み取りする必要があります。
于 2012-10-07T01:58:23.380 に答える