whistler
whistler

Reputation: 886

How can I access the binary format of a file?

I just finished a computer organization course, in which we learned that all files and data are stored in the form of 0's and 1's (bits). However, I'm curious how a programmer can actually access a file's binary representation? That is, how can I see (or access) the 0's and 1's that represent any file on my computer?

Upvotes: 0

Views: 1738

Answers (2)

Alexander
Alexander

Reputation: 1113

You could certainly read the file character by character, assuming Java has or treats characters as unsigned you convert the byte in to an integer - then the decimal value of each byte will be the sum of the specific byte. You can then change its base in to a representable binary form:

String byte = Integer.toBinaryString(integer);

This should be in the Java package java.lang (toBinaryString) and you can loop until the end of file with whichever stream byte wrapper you wish.

EDIT:

To provide insight on your question about how programmers read a binary format (although on the low level)

I am unsure of how to do this in Java, although in C you would create a struct (A container of variables) and read bytes directly in to each member, you could assume the file structure beforehand by the defined file type (i.e. read 4 bytes, make float, read n bytes as vector array)

Upvotes: 0

icktoofay
icktoofay

Reputation: 128993

While it's true that at the most basic level, everything is stored as bits, most processors these days only allow you to access bytes (8 bit blocks). From a byte, however, you can figure out if a bit is one or not.

To get the value of a bit in position pos (from least significant bit, 0, to most significant bit, 7) of byte byte, you could use this code (in C, here, but it's likely valid in many languages):

// bit here is likely 32 bits, but it will only contain 0 or 1,
// based on the value of the bit at pos in byte
int bit=(byte>>pos)&1;

Upvotes: 1

Related Questions