开发者

string to byte array [closed]

开发者_如何学GoIt's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I get very very long packets that are logged into a text file. But some I have to check for errors. example(a very short one):

863900004400003708F72E0000003F2F0000001E2F0000008A2F000000632F000000AE2F000000D42A0000009323000000050000E7FD0700A861006087447E6F02C200608844359D0101A8613B04E0FF43040100009A999941010070420000C842000C005F5F5FC1EEF0FBE6EAE05F5F01020000000000000C00C3F0F3EFEFE05FD0E8F1EAE000FFDE070000B5000000A861661675447F6F02C2294C7744B540000100B54001000000000000000000000000C8420002020103DD07000026010000A861333375447F6F02C252487744B540000100B54001000000000000000000000000C84200020201037E0700002000012D043B0E0000003C0E0000003D0E000000320E000000050000C0C20500A861549B72447E6F02C28FF9AA44CEA9000100CEA901000000008041000048420000C842000900EBF3EAE0F15FEBF2F300010000000000000C00C1EEE3E85F5FD1ECE5F0F2E8D21000000000000000000000000000000000010000FF2E08000007000000A86100C09C440000C0C000C0AB440000

I need an application that'd insert a ',0x' inbetween every byte so that later I can declare it as a static array.

The problem is that if I add this as a string, the compiler gives errors, because the string is too long. For this reason I'd be good if you could help me do this in one of the languages: C/C++,C# or Delphi.


You can use C# to convert your string to a byte array by using:

byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(yourString);


C#:

// get entire string
var contents = File.ReadAllText("filename.txt");
// convert every 2 digits 'AA' into ',0xAA'
contents = Regex.Replace(contents, "..", ",0x$0").Trim(',');
// output to another file
File.WriteAllText("filename2.txt");


In C:

#include <stdio.h>

int main(int argc, char* argv[])
{
    int ch;
    while ((ch = getc(stdin)) != EOF) {
        if (isprint(ch)) {
            if (! isspace(ch)) {
                printf("0x%c", ch);
            } else {
                printf("[0x%X]", ch);
            }
        }
    }
    return 0;
}

To invoke:

Windows:

type filename | program.exe

Unix:

cat filename | ./program

There is a distinction for spaces, tabs, newlines and carriage returns because you will inevitably encounter them in your efforts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜