質問

ねえ私は完全に私の深さから外れていて、私の脳は傷つき始めています.. :(

3バイト配列に収まるように整数を隠してください。

私は持っています:

NSMutableData* data = [NSMutableData data];

 int msg = 125;

 const void *bytes[3];

 bytes[0] = msg;
 bytes[1] = msg >> 8;
 bytes[2] = msg >> 16;

 [data appendBytes:bytes length:3];

 NSLog(@"rtn: %d", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] intValue]);

 //log brings back 0

私の主な問題は、データを送信するために必要な変換であることを実際に正しく変換したことを確認する方法がわからないということだと思います。

どんな助けも大歓迎です!

役に立ちましたか?

解決

組合を使用できます。

union convert {
    int i;
    unsigned char c[3];
};

INTからバイトに変換するには:

union convert cvt;
cvt.i = ...
// now you can use cvt.c[0], cvt.c[1] & cvt.c[2]

バイトからintに変換するには:

union convert cvt;
cvt.i = 0; // to clear the high byte
cvt.c[0] = ...
cvt.c[1] = ...
cvt.c[2] = ...
// now you can use cvt.i

注:この方法での組合の使用は、プロセッサバイトオーダーに依存しています。私が与えた例は、小エンディアンシステム(x86など)で動作します。

他のヒント

32ビットの整数があると仮定します。下の24ビットをバイト配列に入れたい:

int msg = 125;
byte* bytes = // allocated some way

// Shift each byte into the low-order position and mask it off
bytes[0] = msg & 0xff;
bytes[1] = (msg >> 8) & 0xff;
bytes[2] = (msg >> 16) & 0xff;

3バイトを整数に戻すには:

// Shift each byte to its proper position and OR it into the integer.
int msg = ((int)bytes[2]) << 16;
msg |= ((int)bytes[1]) << 8;
msg |= bytes[0];

そして、はい、私はそれを行うためのより最適な方法があることを完全に認識しています。上記の目標は明確です。

ポインターのトリックの少しはどうですか?

int foo = 1 + 2*256 + 3*65536;
const char *bytes = (const char*) &foo;
printf("%i %i %i\n", bytes[0], bytes[1], bytes[2]); // 1 2 3

これを生産コードで使用する場合は、おそらく世話をするべきことがありますが、基本的なアイデアは正気です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top