<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wendy Leung on Medium]]></title>
        <description><![CDATA[Stories by Wendy Leung on Medium]]></description>
        <link>https://medium.com/@wendyiscoding?source=rss-c96b357169a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3OV24dZNBdDtYBicR9Rhfg.jpeg</url>
            <title>Stories by Wendy Leung on Medium</title>
            <link>https://medium.com/@wendyiscoding?source=rss-c96b357169a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:04:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wendyiscoding/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mutability and Immutability in Python — Let’s Break It Down]]></title>
            <link>https://medium.datadriveninvestor.com/mutable-and-immutable-python-2093deeac8d9?source=rss-c96b357169a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2093deeac8d9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Wendy Leung]]></dc:creator>
            <pubDate>Fri, 11 Jan 2019 06:30:27 GMT</pubDate>
            <atom:updated>2019-06-09T23:23:48.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IF-pQPW99uhXbLRM" /></a></figure><h3>Mutability and Immutability in Python — Let’s Break It Down</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*cTD10Cq9OeXxk3ib.jpg" /><figcaption>Mutability or immutability</figcaption></figure><h3><strong>Have you ever modified a variable without knowing it or wanting to?</strong></h3><p>In this article, we’ll address that by covering id and type, mutable objects, immutable objects, why it matters, how differently does Python treat mutable and immutable objects, how are arguments passed to functions, and what does that imply for mutable and immutable objects. I include examples in Python3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JWsk34L1XX2zeFGR.jpg" /><figcaption>Who are you, who am I? Photo Attribution: <a href="https://www.flickr.com/photos/saulalbert/37545736336">https://www.flickr.com/photos/saulalbert/37545736336</a></figcaption></figure><h3><strong>What is id?</strong></h3><pre>id()</pre><p>Id is a built-in function in Python. It gives us the ability to check the unique identifier of an object. Let’s take a look at how this works.</p><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; a<br>1</pre><p>We see that a is an object that contains the value 1. Now let’s check the id, the unique identifier, of that object.</p><pre>&gt;&gt;&gt; id(a)<br>10105088</pre><p>The unique identifier is pointing to a location in memory, which is an object. Let’s try another one.</p><pre>&gt;&gt;&gt; b = 2<br>&gt;&gt;&gt; b<br>2<br>&gt;&gt;&gt; id(b)<br>10105120</pre><p>You can see that id(a) is different from id(b) but we can also run a test.</p><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = 2<br>&gt;&gt;&gt; id(a) == id(b)<br>False</pre><p>Let’s assign another variable to 2 and check the id.</p><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = 2<br>&gt;&gt;&gt; c = 2<br>&gt;&gt;&gt; c<br>2<br>&gt;&gt;&gt; id(c)<br>10105120</pre><p>Hmm, id(c) looks the same as id(b). Why is that? Let’s run a test.</p><pre>&gt;&gt;&gt; id(c) == id(b)<br>True</pre><p>They have the same unique identifier because c is referencing an object that contains the value 2, and b is also referencing the <strong>same object that contains the value 2</strong>. Okay, let that sink in for a moment. Wow, right?</p><p>They’re both pointing to the same object that contains a value 2.</p><pre>&gt;&gt;&gt; id(c)<br>10105120<br>&gt;&gt;&gt; id(b)<br>10105120</pre><p>The object, 10105120, is the unique identifier. It’s the location in memory. Objects can have multiple variables. If you’re debugging a program, this might be a useful function. Let’s now try this with strings.</p><pre>&gt;&gt;&gt; a = &quot;strawberry&quot;<br>&gt;&gt;&gt; b = &quot;strawberry&quot;<br>&gt;&gt;&gt; id(a) == id(b)<br>True<br>&gt;&gt;&gt; a = &quot;strawberry&quot;<br>&gt;&gt;&gt; b = &quot;Strawberry&quot;<br>&gt;&gt;&gt; id(a) == id(b)<br>False</pre><p>What happened here? In the second example above, we used a capital S in variable b’s object. That’s why it was False.</p><p>Let’s look at more examples.</p><pre>&gt;&gt;&gt; a = 256<br>&gt;&gt;&gt; b = 256<br>&gt;&gt;&gt; id(a) == id(b)<br>True<br>&gt;&gt;&gt; a = 260<br>&gt;&gt;&gt; b = 260<br>&gt;&gt;&gt; id(a) == id(b)<br>False</pre><p>Why is it True for 256 but False for 260?</p><p>The reason is that Python keeps an array of integer objects for all integers between -5 and 256. When you create an integer in that range, you get back a reference to the already existing object.</p><p>It does this with two macros, NSMALLNEGINTS and NSMALLPOSINTS. If the value ival satisfies the condition of being between -5 and 256, the function get_small_int is called.</p><pre>#ifndef NSMALLPOSINTS<br>#define NSMALLPOSINTS           257<br>#endif<br>#ifndef NSMALLNEGINTS<br>#define NSMALLNEGINTS           5<br>#endif</pre><pre>#define CHECK_SMALL_INT(ival)<br>    do if (-NSMALLNEGINTS &lt;= ival &amp;&amp; ival &lt; NSMALLPOSINTS) {<br>        return get_small_int((sdigit)ival);<br>    } while(0)</pre><p>Note: You can also use “is” to check if two variables have the same object id.</p><pre>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = list1<br>&gt;&gt;&gt; list1 is list2<br>True</pre><p>Let’s introduce some more terminology.</p><p>The same list above has two different names, list1 and list2, and we can say that it is <strong>aliased</strong>. Variables refer to objects and if we assign one variable to another, both variables refer to the same object. That is what aliasing means.</p><p>Let’s also talk about <strong>cloning</strong>. If we want to modify a list and also keep a copy of the original, we need to make a copy of the list. This process is called cloning. Taking any slice of a list creates a new list.</p><pre>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = list1[:]<br>&gt;&gt;&gt; list1<br>[1, 2, 3]<br>&gt;&gt;&gt; list2<br>[1, 2, 3]<br>&gt;&gt;&gt; list1 is list2<br>False<br>&gt;&gt;&gt; id(list1) == id(list2)<br>False</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*DEFK58E-AupD1uz5.jpg" /><figcaption>Types</figcaption></figure><h3><strong>What is type?</strong></h3><pre>type()</pre><p>In Python, all data is stored in the form of an object. An object has three things: id, type, and value.</p><p>The type function will provide the type of the object that’s provided as its argument.</p><pre>&gt;&gt;&gt; type(2)<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt; type(-6.25)<br>&lt;class &#39;float&#39;&gt;<br>&gt;&gt;&gt; type(2,)<br>&lt;class &#39;tuple&#39;&gt;<br>&gt;&gt;&gt; type(&quot;hello&quot;)<br>&lt;class &#39;str&#39;&gt;<br>&gt;&gt;&gt; type(&#39;A&#39;)<br>&lt;class &#39;str&#39;&gt;<br>&gt;&gt;&gt; type(&#39;346.789&#39;)<br>&lt;class &#39;str&#39;&gt;<br>&gt;&gt;&gt; type([2, 3, 4])<br>&lt;class &#39;list&#39;&gt;<br>&gt;&gt;&gt; type({&#39;category&#39;: &#39;produce&#39;, &#39;count&#39;: 200})<br>&lt;class &#39;dict&#39;&gt;<br>&gt;&gt;&gt; type(print)<br>&lt;class &#39;builtin_function_or_method&#39;&gt;<br>&gt;&gt;&gt; type(type)<br>&lt;class &#39;type&#39;&gt;</pre><p>Like id(), type() is also useful for debugging.</p><h3>What are mutable objects?</h3><pre>Python</pre><pre>Mutable objects:<br>list, dict, set</pre><p>A program stores data in variables that represent the storage locations in the computer’s memory. The contents of the memory locations, at any given point in the program’s execution, is called the program’s <strong>state</strong>.</p><p>Some objects in Python are mutable, and some are immutable. First, we’ll discuss mutable objects. A mutable object is a changeable object and its state can be modified after it is created.</p><pre>&gt;&gt;&gt; my_list = [&#39;cat&#39;, &#39;dog&#39;, &#39;bunny&#39;]<br>&gt;&gt;&gt; my_list<br>[&#39;cat&#39;, &#39;dog&#39;, &#39;bunny&#39;]<br>&gt;&gt;&gt; print(&#39;Address of my_list is: {}&#39;.format(id(my_list)))<br>Address of my_list is: 139929780579208</pre><p>If we want to change the first value in our list and print it out, we can see that the list changed, but the memory address of the list is the same. <strong>It changed the value in place. That’s what mutable means.</strong></p><pre>&gt;&gt;&gt; my_list[0] = &#39;sugar glider&#39;<br>&gt;&gt;&gt; my_list<br>[&#39;sugar glider&#39;, &#39;dog&#39;, &#39;bunny&#39;]<br>&gt;&gt;&gt; print(&#39;Address of my_list is: {}&#39;.format(id(my_list)))<br>Address of my_list is: 139929780579208</pre><p>Let’s look now at the memory addresses of <strong>values of the list </strong>and see what happens before and after we change the value of the first element of the list.</p><pre>&gt;&gt;&gt; my_list<br>[&#39;sugar glider&#39;, &#39;dog, &#39;bunny&#39;]<br>&gt;&gt;&gt; id(my_list)<br>139929780579208<br>&gt;&gt;&gt; my_list[0]<br>&#39;sugar glider&#39;<br>&gt;&gt;&gt; id(my_list[0])<br>139905997708792<br>&gt;&gt;&gt; my_list[0] = &#39;rabbit&#39;<br>&gt;&gt;&gt; id(my_list[0])<br>139905997708400<br>&gt;&gt;&gt; id(my_list)<br>139929780579208</pre><p>The id of my_list[0] is 139905997708792 when the value of the first element is ‘sugar glider’. The id of my_list[0] is 139905997708400 after we change the value to ‘rabbit.’ Notice they are two different ids.</p><p>When we modify a list and change its values in place, the list keeps the same address. However, the address of the value that you changed will have a different address.</p><p>The id of my_list still remained the same at 139929780579208.</p><h3>What are immutable objects?</h3><pre>Python</pre><pre>Immutable objects:<br>integer, float, string, tuple, bool, frozenset</pre><p>An immutable object is an object that is not changeable and its state cannot be modified after it is created.</p><p>In Python, a string is immutable. You cannot overwrite the values of immutable objects.</p><p>However, you can assign the variable again.</p><pre>&gt;&gt;&gt; phrase = &#39;how you like me now&#39;<br>&gt;&gt;&gt; phrase<br>how you like me now<br>&gt;&gt;&gt; phrase = &#39;do you feel lucky&#39;<br>&gt;&gt;&gt; phrase<br>do you feel lucky</pre><p>It’s not modifying the string object; it’s creating a new string object.</p><p>To see this in more detail, we can utilize the id function that we learned earlier. Recall that id() function prints out the memory address.</p><pre>&gt;&gt;&gt; phrase = &#39;how you like me now&#39;<br>&gt;&gt;&gt; print(&#39;Address of phrase is: {}&#39;.format(id(phrase)))<br>Address of phrase is: 139929793080104<br>&gt;&gt;&gt; phrase = &#39;do you feel lucky&#39;<br>&gt;&gt;&gt; print(&#39;Address of phrase is: {}&#39;.format(id(phrase)))<br>Address of phrase is: 139929792606832</pre><p>Since a string is immutable, it created a new string object. The memory addresses do not match.</p><p>Let’s try to change a single character of the phrase.</p><pre>&gt;&gt;&gt; phrase[0] = &#39;D&#39;<br>...<br>TypeError: &#39;str&#39; object does not support item assignment</pre><p>We get a TypeError because strings are immutable. We can’t change the string object.</p><p>Let’s also talk about tuples.</p><p>Immutability on tuples is only partly true. The tuple itself cannot be modified, but objects referenced by the tuple can be modified. If the tuple has an immutable field like a string, then the tuple cannot be modified and it is sometimes called “non-transitive immutability.” But a mutable field like a list can be edited, even if it’s embedded in the “immutable” tuple.</p><h3>Why do mutable and immutable objects matter and how differently does Python treat them?</h3><p>Numbers, strings, and tuples are immutable. Lists, dictionaries, and sets are mutable, as are most new objects you’ll code with classes.</p><p><strong>Immutability may be used to ensure that an object remains constant throughout your program. The values of mutable objects can be changed at any time and place, whether you expect it or not.</strong></p><p>You can change a single value of a mutable data type and it won’t change its memory address. However, you can’t change a single value of an immutable type. It will throw an error.</p><h3>How are arguments passed to functions and what does that imply for mutable and immutable objects?</h3><p>The way that the Python compiler handles function arguments has to do with whether the objects in the function arguments are mutable or not immutable.</p><p>If a mutable object is called by reference in a function, the original variable may be changed. If you want to avoid changing the original variable, you need to copy it to another variable.</p><p>When immutable objects are called by reference in a function, its value cannot be changed.</p><p>Let’s look at this Python script and guess what it will print:</p><pre>def increment(n):<br>    n += 1<br><br>b = 9<br>increment(b)<br>print(b)</pre><p>Think about it and then continue reading for the answer.</p><p>The variable b refers to the object with value 9. When we pass b as a function argument to increment(n) function, the local variable n refers to the same object. However, <strong>integers are immutable </strong>so we need to create a new object with the value 10 and assign it to the variable n. The variable n is pointing to a different object from what b is pointing. Now, n refers to an object with value 10, but b still refers to an object with value 9. When we print(b), we get the answer 9.</p><p>The answer: 9</p><p>Let’s look at another Python script and guess what it will print:</p><pre>def increment(n):<br>    n.append(4)<br><br>my_list = [1, 2, 3]<br>increment(my_list)<br>print(my_list)</pre><p>Think about it, perhaps draw a visualization, and then continue reading for the answer.</p><p>The variable my_list refers to a list object that contains references to three integers. Lists are mutable but integers are immutable. When we pass my_list as a function argument to increment(n) function, the function has the local variable n refer to the same object that my_list refers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*3L57bSQ8gLucd1JEK4lrPQ.png" /></figure><p>Since lists are mutable, the .append() method is able to modify the list in place. No new object is created and when we print my_list, we get the answer [1, 2, 3, 4].</p><p>The answer: [1, 2, 3, 4]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Ys1qM50aTx4KCGRTDdrewg.png" /></figure><p>Let’s look at another Python script to understand more about function parameters and why mutability and immutability matter.</p><pre>def assign_value(n, v):<br>    n = v<br><br>list1 = [1, 2, 3]<br>list2 = [4, 5, 6]<br>assign_value(list1, list2)<br>print(list1)</pre><p>Think about it and then continue reading for the answer.</p><p>We pass both lists as function parameters to the assign_value(n, v) function. The function has the local variable n refer to the same object that list1 refers, and the local variable v refers to the same object that list2 refers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*Ed0_H11yrSd0Qyc6X7mQ5w.png" /></figure><p>The function body reassigns n to what v is referring. Now n and v are referring to the same object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*dlr6Z0toJSxlN02yytM-eQ.png" /></figure><p>The variables n, v, and list2 all point to the list object [4, 5, 6], while list1 still points to the list object [1 2, 3]. This is why when we print list1, we get the answer: [1, 2, 3]</p><p>The answer: [1, 2, 3]</p><p>How do we write a function that returns a copy of a list? Here’s one way of doing it. Let’s look at copy_list(l) function.</p><pre>def copy_list(l):<br>    return l[:]<br>    <br>my_list = [1, 2, 3]<br>new_list = copy_list(my_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*zG2k3oFhHGY0XnukrK0b7g.png" /></figure><p>We pass my_list as a function parameter to the copy_list(l) function. The function has the local variable l refer to the same object that my_list refers. When we use the slice operation [:], it creates a copy of a list and when we return that copy, we are returning the reference to that copy. Now, new_list refers to a different object than what my_list refers.</p><pre>&gt;&gt;&gt; def copy_list(l):<br>...    return l[:]<br>...    <br>&gt;&gt;&gt; my_list = [1, 2, 3]<br>&gt;&gt;&gt; new_list = copy_list(my_list)<br>&gt;&gt;&gt; my_list<br>[1, 2, 3]<br>&gt;&gt;&gt; new_list<br>[1, 2, 3]<br>&gt;&gt;&gt; my_list == new_list<br>True<br>&gt;&gt;&gt; my_list is new_list<br>False<br>&gt;&gt;&gt; id(my_list) == id(new_list)<br>False</pre><p>I know we covered a lot here, so take a deep breath, practice, repeat, and you’ll soon be able to explain these concepts to other people. Thanks for reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2093deeac8d9" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/mutable-and-immutable-python-2093deeac8d9">Mutability and Immutability in Python — Let’s Break It Down</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Talk Two’s Complement. It’s Almost As Easy As 1, 2, 3…]]></title>
            <link>https://medium.datadriveninvestor.com/twos-complement-a283b2448135?source=rss-c96b357169a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a283b2448135</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Wendy Leung]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 03:43:22 GMT</pubDate>
            <atom:updated>2018-12-09T08:47:05.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_zwOacVVV0SQGpOj.jpg" /></figure><p>Do you know the lyrics from The Jackson 5 song, “ABC”? I’m going to show you that two’s complement is almost as “easy as…1, 2, 3.”</p><blockquote>We learned when we were little to count with the decimal system (base 10), starting with 0.</blockquote><pre>   0<br>   1<br>   2<br>   3<br>   4<br>   5<br>   6<br>   7<br>   8<br>   9<br>  10<br>  11<br>  12<br>  ..<br>  ..<br>  99<br> 100<br> 101</pre><p>What happens when we reach the number 10? The rightmost digit flips to 0 and we add a 1 on the left to begin the tens place.</p><p>Each digit on the left increases by another power.</p><p>Hundredths place + Tens place + Ones place</p><p>10² + 10¹ + 10⁰</p><p>Let’s illustrate with the number 108:</p><p>(10² * 1) + (10¹ * 0) + (10⁰ * 8) = 108</p><blockquote>Now let’s talk binary.</blockquote><p>Your computer stores everything as a series of 0’s and 1’s, including numbers, and it operates in binary (base 2).</p><p>… + 2⁶ + 2⁵ + 2⁴ + 2³ + 2² + 2¹ + 2⁰</p><p>Do you see that the exponent increases by 1 each time on the left?</p><p>That number 108 in base 10 would look different in base 2.</p><p>(2⁶ * 1) +(2⁵ * 1) + (2⁴ * 0) + (2³ * 1) + (2² * 1) + (2¹ * 0) + (2⁰ * 0) = 1101100</p><pre>Base 10: 108<br>Base 2: 1101100</pre><p>Okay, now you try! Pick a number, any number, and take a moment to do the same thing.</p><blockquote>So what is two’s complement?</blockquote><p>Two’s complement refers to how numbers are stored in memory. The smallest memory is a bit. And each bit can be 0 for “off” or 1 for “on.”</p><p>To see how a computer stores a positive number, write out the number in binary. Let’s take number 28 (base 10) as an example.</p><p>To write it out in binary, I use this method:</p><ol><li>Find the largest number that does not exceed my number.</li></ol><p>2⁵ + 2⁴ + 2³ + 2² + 2¹ + 2⁰</p><p>2⁵ is 32, and that exceeds 28, so let’s try the next smallest number on the right.</p><p>2⁴ is 16, and it does <strong>not</strong> exceed 28. That’s my starting point then, and I will mark 1 underneath it to indicate that bit is “on.”</p><p>2⁴<br>1</p><p>2. Calculate which values, from the bits to the right, when added with 2⁴, will equal 28. I am essentially figuring out which bits to turn on and which to leave off. When I am done, I will have the binary number.</p><p>2⁴ + 2³ + 2² + 2¹ + 2⁰<br>1….. 1…..1…..0…..0</p><p>(2⁴ * 1) + (2³ * 1) + (2² * 1) + (2¹ * 0) + (2⁰ * 0)</p><pre>Base 10: 28<br>Base 2 (binary): 11100</pre><blockquote>This is comparable to making change for someone…</blockquote><p>Pretend that you sell something for 27 cents. The buyers give you a $1 bill.</p><p>You have a choice of returning change in quarters, dimes, nickels, and pennies. You can give the change back in all pennies (73 cents), but that would be a hassle, and most likely, you would upset the buyers. So let’s return the change starting with the largest coin possible. To equal change in 73 cents, you give them:</p><p>2 quarters, 2 dimes, 0 nickels, and 3 pennies.</p><blockquote><strong>You saw how positive numbers are stored, but what about negative numbers?</strong></blockquote><p>To find the two’s complement, flip all the bits and add 1.</p><p>So let’s take that same number of 28 in base 10, and convert it to binary:</p><p>00011100</p><p>Now we flip the bits:</p><p>11100011</p><p>And add 1:</p><p>11100100</p><pre>Base 10: 28<br>28 in binary form: 00011100</pre><pre>Base 10: -28<br>-28 in binary form: 11100100</pre><p>Now you know how positive numbers and negative numbers are stored in memory. It’s almost as easy as A, B, C…. 1, 2, 3….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*hp6rkzmEoPili_YN.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a283b2448135" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/twos-complement-a283b2448135">Let’s Talk Two’s Complement. It’s Almost As Easy As 1, 2, 3…</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Do C Static Libraries Have in Common With Your Kitchen]]></title>
            <link>https://medium.datadriveninvestor.com/c-static-libraries-e620f1c1514f?source=rss-c96b357169a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e620f1c1514f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[static-library]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Wendy Leung]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 02:30:56 GMT</pubDate>
            <atom:updated>2019-07-10T14:54:37.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr0On99ZqJwWGL7EIeQkJQ.png" /></figure><p>Let’s dive into a short bit of C source code:</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>    printf(&quot;Hello, World\n&quot;);<br>    return (0);<br>}</pre><p>At the top, we included &lt;stdio.h&gt;, the standard input output header, in which the printf function is declared.</p><h3>What Are Header Files and What Are Libraries</h3><p><strong>Header files</strong>, such as stdio.h, contain function declarations and macro definitions to be shared between source files. They tell the compiler how to call some functionality, <strong>without knowing how the functionality works</strong>.</p><p><strong>Libraries</strong> are where the <strong>actual functionality is implemented</strong> because they contain the function definition. Libraries have two types:</p><ul><li>Static (we’ll discuss static libraries in this blog post)</li><li>Dynamic (to be discussed at a later time)</li></ul><p>A library is essentially a collection of functions, variables, and symbols.</p><h3>What Do C Static Libraries Have in Common With Your Kitchen</h3><p>Imagine that your family likes to eat jerk chicken, meat lasagna, and pumpkin pie every week. They are picky eaters and you make it the same way every week because you know that the recipe works.</p><p>Now you want easy and fast access to your recipes, so you keep them together and even index them.</p><p>Static libraries are like the recipes you use in your kitchen because you can keep a collection of functions in an easily accessible, indexed, and reusable manner.</p><p><strong>Reasons to Use Static Libraries:</strong></p><ul><li>As programs grow, using libraries makes it easier to manage code.</li><li>You don’t have to keep rewriting the same functions that you use frequently.</li><li>They are great for reusability, as well as collaborating with other programmers.</li><li>If your object files are in a library and indexed, fewer files need to be searched and opened, and access is faster.</li></ul><h3>How Do Static Libraries Work</h3><p>Recall the <a href="https://medium.com/datadriveninvestor/compilation-process-db17c3b58e62">four steps of compilation</a>.</p><ol><li>Preprocessing: removes comments and deals with # directives</li><li>Compilation: pre-processed code is converted to assembly code</li><li>Assembly: code is converted to machine code (zeros and ones), also known as object code</li><li>Linking: produces the executable</li></ol><p>In Step 4, linking tries to resolve referenced symbols and locate in which object file the symbols are defined. <strong>The object code in your program is copied into the executable.</strong></p><p>If we have a static library with object files and an index of defined symbols (versus object files on different disks), the linking process is faster. Our program is also more portable because we don’t have to depend on the particular libraries that are on the system.</p><h3>How to Create Static Libraries</h3><ol><li><strong>Create a header file with your function prototypes and include the header file in your C source files.</strong></li></ol><pre>#ifndef WENDYBLOGTECH_H<br>#define WENDYBLOGTECH_H</pre><pre>int _putchar(char c);<br>int _isalpha(int c);<br>int _abs(int n);<br>int _strlen(char *s);<br>void _puts(char *s);<br>char *_strcpy(char *dest, char *src);<br>char *_strcat(char *dest, char *src);<br>char *_strncat(char *dest, char *src, int n);<br>int _strcmp(char *s1, char *s2);<br>char *_memcpy(char *dest, char *src, unsigned int n);<br>char *_strstr(char *haystack, char *needle);</pre><pre>#endif</pre><p>2. <strong>Compile your C source files without linking by using the gcc</strong><strong>-cflag.</strong></p><pre>gcc -Wall -pedantic -Werror -Wextra -c *.c</pre><p>The -c flag compiles your C source files but does not link. You’ll now see files with .o extension in your directory.</p><pre>0-strcat.o<br>1-memcpy.o<br>1-strncat.o<br>2-strlen.o<br>2-strncpy.o<br>3-puts.o<br>3-strcmp.o<br>4-isalpha.o<br>5-strstr.o<br>6-abs.o<br>_putchar.o</pre><p>3. <strong>Create a static library (archive) with the </strong><strong>artool.</strong></p><pre>ar -rc &lt;libraryname.a&gt; *.o</pre><pre>example: ar -rc libwendyblogtech.a *.o</pre><p>The -rflag creates a new archive and then adds the objects to the archive. The -cflag suppresses the output that says we’re creating a new archive.</p><p>4. <strong>Use the </strong><strong>artool with the </strong><strong>-tflag to display a list of the contents of the archive.</strong></p><pre>ar -t &lt;libraryname.a&gt;</pre><pre>example: ar -t libwendyblogtech.a</pre><p>5. <strong>Use </strong><strong>ranlibto generate an index to the contents of the archive.</strong></p><pre>ranlib &lt;libraryname.a&gt;</pre><pre>example: ranlib libwendyblogtech.a</pre><p>6. <strong>Use</strong><strong>nmto list symbols from the object files.</strong></p><pre>$ nm libwendyblogtech.a<br><br>0-strcat.o:<br>0000000000000000 T _strcat<br><br>1-memcpy.o:<br>0000000000000000 T _memcpy<br><br>1-strncat.o:<br>0000000000000000 T _strncat<br><br>2-strlen.o:<br>0000000000000000 T _strlen<br><br>2-strncpy.o:<br>0000000000000000 T _strncpy<br><br>3-puts.o:<br>                 U _putchar<br>0000000000000000 T _puts<br><br>3-strcmp.o:<br>0000000000000000 T _strcmp<br><br>4-isalpha.o:<br>0000000000000000 T _isalpha<br><br>5-strstr.o:<br>0000000000000000 T _strstr<br><br>6-abs.o:<br>0000000000000000 T _abs<br><br>_putchar.o:<br>0000000000000000 T _putchar<br>                 U write</pre><h3>How to Use Static Libraries</h3><p>Now that we have our static library, let’s invoke the library after writing a program that uses the _puts function from the library.</p><p>Note that at the top, we put the filename in “ ” quotes instead of &lt;&gt; brackets because wendyblogtech.h is our own header file and not a system header file.</p><pre>#include &quot;wendyblogtech.h&quot;</pre><pre>int main(void)<br>{<br>    _puts(&quot;\&quot;That&#39;s how you create a static libary.\&quot;&quot;);<br>    return (0);<br>}</pre><p><strong>Invoking a library:</strong></p><pre>Example of invoking libwendyblogtech.a:</pre><pre>gcc quote.c -L. -lwendyblogtech -o quote</pre><p>-Llooks in the directory for library files and because we have a period right after it, it will look in the current directory. <br>-llinks the library file and automatically adds the lib prefix and the .a, hence the reason why we don’t type the entire libwendyblogtech.a</p><p><strong>Now we run our executable program </strong><strong>./quote and see the output:</strong></p><pre>&quot;That&#39;s how you create a static library.&quot;</pre><p>There you have it… static libraries are like the recipes you use in your kitchen because you can keep a collection of functions in an easily accessible, indexed, and reusable manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e620f1c1514f" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/c-static-libraries-e620f1c1514f">What Do C Static Libraries Have in Common With Your Kitchen</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Compilation Process Works for C Programs]]></title>
            <link>https://medium.datadriveninvestor.com/compilation-process-db17c3b58e62?source=rss-c96b357169a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/db17c3b58e62</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[gcc]]></category>
            <dc:creator><![CDATA[Wendy Leung]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 01:06:07 GMT</pubDate>
            <atom:updated>2018-09-13T19:10:32.929Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>C is a compiled language. </strong>Its source code is written using any editor of a programmer’s choice in the form of a text file, then it has to be compiled into machine code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g26yvU2fJFVfAwBz.jpg" /></figure><p>C source files are by convention named with <strong>.c extension</strong> and we use the command “gcc” to compile C source files. <em>(GCC stands for GNU Compiler Collection and it is a compiler system produced by the GNU Project.)</em></p><p><strong>Four Steps of Compilation: preprocessing, compiling, assembly, linking.</strong></p><blockquote><strong><em>Preprocessing:</em></strong></blockquote><p>Preprocessing is the first step. The preprocessor obeys commands that begin with # (known as directives) by:</p><ul><li>removing comments</li><li>expanding macros</li><li>expanding included files</li></ul><p>If you included a header file such as #include &lt;stdio.h&gt;, it will look for the stdio.h file and copy the header file into the source code file.</p><p>The preprocessor also generates macro code and replaces symbolic constants defined using #define with their values.</p><blockquote><strong><em>Compiling:</em></strong></blockquote><p>Compiling is the second step. It takes the output of the preprocessor and generates assembly language, an intermediate human readable language, specific to the target processor.</p><blockquote><strong><em>Assembly:</em></strong></blockquote><p>Assembly is the third step of compilation. The assembler will convert the assembly code into pure binary code or machine code (zeros and ones). This code is also known as object code.</p><blockquote><strong><em>Linking:</em></strong></blockquote><p>Linking is the final step of compilation. The linker merges all the object code from multiple modules into a single one. If we are using a function from libraries, linker will link our code with that library function code.</p><p>In static linking, the linker makes a copy of all used library functions to the executable file. In dynamic linking, the code is not copied, it is done by just placing the name of the library in the binary file.</p><p><strong>Let’s now compile! For our example, we’ll use “main.c” as our source file.</strong></p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>      printf(&quot;Hello, World!\n&quot;);<br>      return (0);<br>}</pre><p>At the shell prompt, enter the command “gcc main.c” and hit Enter. If it successfully compiles, the shell prompt will be displayed again. If it does not compile, it will display error message(s).</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ gcc main.c<br>vagrant@vagrant-ubuntu-trusty-64:~$ ls<br>a.out main.c</pre><p><strong>After main.c is compiled, type the command “ls” to list your directory contents and you will see an executable file named a.out. </strong>To run the program, type “./a.out” at the shell prompt and hit Enter. Yay, we see the correct output “Hello, World!” followed by a newline.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ ./a.out<br>Hello, World!<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><p>If you don’t want your output file to be named a.out, which is the default output filename, you can specify a different output filename with the -o option.</p><pre>gcc -o &lt;desired_output_filename&gt; &lt;source filename&gt;</pre><p>Let’s see an example below where we want the output file to be named main.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ gcc -o main main.c<br>vagrant@vagrant-ubuntu-trusty-64:~$ ls<br>main main.c<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><p>To run the main program, we type “./main” into the terminal.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ ./main<br>Hello, World!<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><blockquote><em>If you make changes to your code (i.e. make any changes to your source file), you will need to save and recompile.</em></blockquote><h4>In some instances, the C source file will not successfully compile.</h4><p>Read the error messages for clues on how to fix.</p><p>Below, we left out the semicolon at the end of the printf statement.</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>      printf(&quot;Hello, World!\n&quot;)<br>      return (0);<br>}</pre><p>An error message displays that a semicolon was expected before return.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ gcc -o main main.c<br>main.c: In function &#39;main&#39;:<br>main.c:5:7: error: expected &#39;;&#39; before &#39;return&#39;<br>       return (0);<br>       ^<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><p>If we add the semicolon back…</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>      printf(&quot;Hello, World!\n&quot;);<br>      return (0);<br>}</pre><p>…and then recompile, the error message will be gone.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ gcc -o main main.c<br>vagrant@vagrant-ubuntu-trusty-64:~$ ./main<br>Hello, World!<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><h4>Even if your source file compiles, check if your output is correct.</h4><p>Here is an example of a source file that compiles…</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>      printf(&quot;The sum of 9+2 is: %i\n&quot;, 10);<br>      return (0);<br>}</pre><p>…but the output is not correct.</p><pre>vagrant@vagrant-ubuntu-trusty-64:~$ ./main2<br>The sum of 9+2 is: 10<br>vagrant@vagrant-ubuntu-trusty-64:~$</pre><p>Oops, we have an error due to a typo in the source code.</p><pre>printf(&quot;The sum of 9+2 is: %i\n&quot;, 10);</pre><p>We know that 9+2 = 11 but the compiler did as the code instructed in the above line. It substituted the number 10 into the format specifer %i.</p><p>The correct code would have been:</p><pre>#include &lt;stdio.h&gt;</pre><pre>int main(void)<br>{<br>      printf(&quot;The sum of 9+2 is: %i\n&quot;, 11);<br>      return (0);<br>}</pre><p>To sum up, the four steps of compilation are: <strong>preprocessing, compiling, assembly, linking.</strong></p><p>Read the man page on gcc for more information. Happy coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVHP_CXqF94VJq31fIMR0w.png" /><figcaption>top of man page for gcc</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db17c3b58e62" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/compilation-process-db17c3b58e62">How the Compilation Process Works for C Programs</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>