In this exercise I am using Visual Studio 2017 and the std_lib_facilities header provided by Stroustrup.
Chapter 17 // Exercise 1, 2, 31. What is the output format of pointer values on your implementation? Hint: don't read the documentation.
2. How many bytes are there in an int? In a double? In a bool? Do not use of sizeof except to verify your answer.
3. Write a function, void to_lower(char* s), that replaces all uppercase characters in the C-style string s with their lowercase equivalents. For example, Hello, World! becomes hello, world!. Do not use any standard library functions. A C-style string is a zero-terminated array of characters. So if you find a char with the value 0 you are at the end.
1. Addresses are printed in capitals as "010FFA44", so in hex without the 0x prefix.
2. At least on my pc an int is 32 bits (4 bytes), a double is 64 bits (8 bytes) and a bool is 8 bits (1 byte). I'm not sure if he wanted us to verify this?
3. I used some of my assembly knowledge to do this. ASCII is very clever and well thought out. When it comes to letters, lowercase characters always have their 5th bit set to 1 and uppercase characters have it set to 0; so you can easily switch between upper and lower by just inverting bit 5.
That's what I did here:
On line 22, we access the contents of s, then OR bit number 5 with 1. As uppercase are 0 in bit 5, when you OR 0 with 1, you get 1, so it flips the upper character to lower.
This does not affect already lower case letters or punctuation (as 1 OR 1 is 1). Some more examples:
A warning; s will now be pointing at the end of the array. You can also do while(s[i] != 0; ++i) to avoid this (where i is the length of the array) or assign the pointer to another pointer for the function.
No comments:
Post a Comment