COMP10002-Notes

View on GitHub

Numbers Representation and Files

Data is represented as 1 and 0 in computers. This is done with transistor devices that can maintain a constant state of 1 (positive voltage) and 0 (no voltage). We can represent numbers with 1s and 0s by using the binary number system.

Binary numbers (base 2) are very similar to decimals (base 10)

Note that n^0 = 1 for any n.

Binary addition

1001 + 0011 = 1100

Hexadecimals

Hexadecimals is a number in base 16. The digits in hexadecimal are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Converting between binary and hexadecimal is actually really convenient, because 16 = 2^4, each hexadecimal digit represents 4 bits in binary

Twos Complement

How do we represent negative numbers? One method is to dedicate a bit at the start of the number to indicate the sign of the number (0 - positive, 1 - negative).

But using a sign bit has two problems:

Twos complement is commonly used to address these two problems. For a number with width w, the first bit has a value of -2^(w-1)

For a 4 bit number:

There is only one representation of zero: 0000, and we can add negative and positive numbers using normal binary addition.

1001 (-7) + 0010 (2) = 1011 (-5)

Converting between positive to negative

There is a trick to calculate the twos complement of -n if you already know the binary of n

  1. Flip all the bits
  2. Add 1

Example for a 4 bit binary:

The same holds for converting a negative number positive

Proof:

Flipping all the bits of XXXX is equivalent to 1111 - XXXX

Flip(XXXX) + 0001 = 1111 - XXXX + 0001 = -1 - n + 1 = -n

Files

File handling in C revolves around the FILE struct defined by stdio.h

You can open a file using FILE *file_ptr = fopen("./filename.txt", mode);

The mode parameter determines what can be done to the opened file

To close a file, use fclose(file_ptr);

Always close files at the end of your program.

Reading and writing text to a file is very similar to functions for stdin/stdout

    char c = fgetc(file_ptr);
    fputc(c, file_ptr);
    fprintf(file_ptr, "%d...", num, ...);
    fscanf(file_ptr, "%d...", &num, ...);

Sometimes we want to read and write binary directly. This is useful if the file is not a text file (e.g. executables, object files, data files, video files…)

In that case use

    size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
    size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Note that fread and fwrite can be used to write arrays.