Writing a C function that uses pointers and bit operators to change one bit in memory?

First off, here is the exact wording of the problem I need to solve:

The BIOS (Basic Input Output Services) controls low level I/O on a computer. When a computer first starts up the system BIOS creates a data area starting at memory address 0x400 for its own use. Address 0x0417 is the Keyboard shift flags register, the bits of this byte have the following meanings:

Bit Value Meaning
7    0/1  Insert off/on
6    0/1  CapsLock off/on
5    0/1  NumLock off/on
4    0/1  ScrollLock off/on
3    0/1  Alt key up/down
2    0/1  Control key up/down
1    0/1  Left shift key up/down
0    0/1  Right shift key up/down

This byte can be written as well as read. Thus we may change the status of the CapsLock, NumLock and ScrollLock LEDs on the keyboard by setting or clearing the relevant bit. Write a C function using pointers and bit operators to turn Caps lock on without changing the other bits.

Our teacher didn't go over this at all, and I've referenced the textbook and conducted many Google searches looking for some help.

I understand how bitwise operators work, and understand that the solution is to OR this byte with the binary value '00000010'. However, I'm stuck when it comes to implementing this. How do I write this in C code? I don't know how to declare a pointer to exactly 1 byte of memory. Besides that, I'm assuming the answer looks like the following (with byte replaced with something proper):

byte* b_ptr = 0x417;
(*b_ptr) |= 00000010;

Is the above solution correct?


unsigned char is the typical synonym for byte. You can typedef byte to mean that if it's not available.

That notation you're using is decimal. The notation for a binary number is easiest in hex, so I'd just use 0x02 instead of the 00000010, which is actually octal notation for a literal number.

I think that you've reversed the order of the bits. My guess is that the bits are numbered most - least significant, so in the solution you propose, the bitmask 00000010 is left shift.

Otherwise, assuming byte is typedef'd to unsigned char, the syntax of the byte * b_ptr = 0x417; will point you at memory address 0x417, which is what you want.

Need Your Help

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space

algorithm data-structures tree binary-tree binary-search-tree

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space.

Elasticsearch return a field

r elasticsearch

I'm using elasticsearch with R for data mining purposes.I'm using shakespeare dataset. I want to retrieve just the text of the field text_entry