0

私は小さな資産を持っていて、バイトを埋め込みたいと思っていました。アセットを取得し、バイトを出力してから、バイトをバイト配列に入れ、それらのバイトを文字列にロードしました。エンディアンの問題のようです。ここで何が間違っていますか?

BytePrinter.app

 const char *helloworldc = "Hello, World!";
 NSString *helloworld = [NSString stringWithUTF8String:helloworldc];
 NSData *data = [helloworld dataUsingEncoding:NSUTF8StringEncoding];
 NSLog(@"%@", [data description]);

出力:

<48656c6c 6f2c2057 6f726c64 21>

ByteImporter.App

  const uint32_t bytes[] = {0x48656c6c, 0x6f2c2057, 0x6f726c64, 0x21};
  NSString *helloworld = [[NSString alloc] initWithBytes:bytes
                                                  length:sizeof(bytes)
                                                encoding:NSUTF8StringEncoding];
  NSLog(@"%@", helloworld);

出力:

lleHW ,odlro!
4

4 に答える 4

2

[data descriptions]4 バイトでグループ化されたバイト単位の出力を返します。

文字列をハードコーディングする場合は、次のコードを使用します。

const unsigned char bytes[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21};
NSString *helloworld2 = [[NSString alloc] initWithBytes:bytes
                                                length:sizeof(bytes)
                                              encoding:NSUTF8StringEncoding];
NSLog(@"%@", helloworld2);

私のコードは正しい文字列を返します

何かを最適化したい場合 (質問: 何?)、エンディアンに注意し、uint32_tそれに応じて配列を修正する必要があります。

更新: NSData によって必要なハードコード配列を生成できるコードがあります:

const char *helloworldc = "Hello, World!";
NSString *helloworld = [NSString stringWithUTF8String:helloworldc];
NSData *data = [helloworld dataUsingEncoding:NSUTF8StringEncoding];

NSMutableString *outStr = [[NSMutableString alloc] init];

unsigned char *ubytes = (unsigned char*)[data bytes];

for (int i = 0; i < [data length]; i++) {
    [outStr appendFormat: @"0x%02x, ", ubytes[i]];
}

NSLog(@"%@", outStr);

出力では、次0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21,のような文字列が得られるため、その周りにブレーサーを追加する必要があります。

于 2013-04-17T20:54:01.793 に答える
0

確かにエンディアンの問題のように見えます。代わりにcharorの配列を使用します。unichar

于 2013-04-17T20:42:43.200 に答える
0

これは、実際には古典的なエンディアンの問題ではありません。これは、データが「通常の」人間が読める出力を使用して出力されるためです (とにかく、エンディアンにも関連しています)。

于 2013-04-17T20:45:11.890 に答える