kouri
kouri

Reputation: 167

How to read a binary field within a text file

I have a fixed width text file that I am using streamreader/readline() to read at the moment.

There's one field that when I open in notepad++ looks like this

[NUL][NUL][NUL][SUB]

Everything else is normal text. I know this field is meant to be 4 characters and represents a count so should look like this '0001'

How can I read it and convert into '0001'

Upvotes: 1

Views: 248

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

I'm not sure what the "SUB" is meant to correspond to - but if it's read as U+0001, you could always use:

for (int i = 0; i < 4; i++) {
    chars[i + index] = (int) chars[i + index] + '0';
}

(Assuming you have a char[] called chars, with the 4 bytes starting at index.)

The first thing to check is whether you actually read the characters properly to start with. It's frankly a bit dodgy to have a "text" file with binary data in to start with, but if it's only bytes 0-9, then in most encodings I'd expect that to correspond to U+0000 to U+0009.

Upvotes: 3

Related Questions