Skip to content

Accessing individual bits on a Commodore PET

On a Commodore PET, each byte that can be read using the PEEK function, and set using the POKE statement. A byte consist of 8 bits, and represent a number between 0 and 255. This code writes the value 5 to the memory address 1020, and then reads it back. The output is of course 5.

POKE 1024, 5
PRINT PEEK(1024)

The POKE statement affects all eight bits at the given address (1024), but bits can be filtered out using logical operators AND and OR. The first (from right to left) of the eight bits represents the value 1, the second bit represents 2, the third 4, the fourth 8, the fifth 16, the sixth 32, the seventh 64 and the last bit represents the value 128.

Since the value 5 is stored at 1024, you would expect all the bits being 0 except the first and the third, since 1 + 4 equals 5. This code reads the first four bits at 1024, and the output is 1, 0, 4 and 0. 1 because the first bit (representing 1) is set, 0 because the second isn’t set, 4 because the third (representing 4) is set and 0 because the fourth isn’t set.

PRINT PEEK(1024) AND 1 : REM Read bit 1 - (1 if set)
PRINT PEEK(1024) AND 2 : REM Read bit 2 - (2 if set)
PRINT PEEK(1024) AND 4 : REM Read bit 3 - (4 if set)
PRINT PEEK(1024) AND 8 : REM Read bit 4 - (8 if set)

Multiple bits can also be read. This code reads both the first and the third bit on the address 1024:

PRINT PEEK(1024) AND 5

The result will be 0 if neither is set, 1 if the first is set, 4 if the second is set and 5 if both the first and third is set. The bit pattern of the value is 00000101, so the bits that are pointed out are the first and the third (from right to left).

Also, you can set individual bits. OR [n] turns a bit on, where [n] is the value that the bit represents. 1, 2, 4, 8, 16, 32, 64 or 128. This code turns on the last bit at 1024:

POKE 1024, PEEK(1024) OR 128

The bit pattern at 1024 is now 10000101. The value that is stored at 1024 is 133, because 1 + 4 + 128 equals 133. To turn the last bit (128) back to zero, use AND together with bit pattern that contains a one at all positions that you want the existing flag to remain, and 0 at the positions you want to turn bytes off. To turn the last bit from the right off, you would want a bit pattern that looks like this: 01111111. All bytes remains, but the last bit from the right is 0. The number 127 has this pattern.

POKE 1024, PEEK(1024) OR 127

Now, the bit pattern at 1024 is changed back from 10000101 to 00000101. The value that is stored in the byte at 1024 is now 5 again.

What can be done with this knowledge?

Categories: Geeky.

Tags:

Visual Basic: The coolest code editor you ever saw

Let’s say that you’re typing a word.

As you type…

…the IntelliSense filters out the word you are typing.

If you type something that isn’t in the list, the list is closing.

If you decide that the last character you typed is wrong, use backspace to delete it. Instantly, the IntelliSense is displayed again, with the possible option selected.

The C# editor has a behavior that is similar to this, but if you go pass an membership access operator, or something like that, the C# IntelliSense is completely lost. You can bring it up again by deleting the line, and start typing again, or by pressing Ctrl+J. The Visual Basic editor picks up automatically, as shown above, whenever you press backspace to delete a word.

Another big advantage in the Visual Basic editor is the enumeration awareness. The Visual Basic editor recognizes when an enumeration is an available option, and provides possible options from the right location in the framework. The C# editor seems very unaware of enumerations, and you might have to look up enumerations that you are unfamiliar of, in the Object Browser by pressing Ctrl+Alt+J.

Demonstrated here:

Categories: Visual Studio 10.

Visual Basic: Serious error trapping

The concept of filtering by exception type is familiar to any C# programmer. Visual Basic takes this one step further by also allowing a logical condition that also needs to be true for the block to be executed. If this feature is used, you can have one Try block with multiple Catch section that filters on the same exception class. This is not possible in C# and not allowed in VB without this extra logical condition. The result is better readability and a more logical structure.

Imagine that you want to do an iteration, that fails after three errors. This is the ugly version:

//Do something 10 times, bail after 3 errors.
for (int x = 0; x < 10; x++)
{
   try
   {
      Console.WriteLine("Try something.");
      //This operation will fail.
      throw new Exception();
   }
   catch (Exception ex)
   {
      Console.WriteLine("Failed.");
      if (x >= 2)
      {
         Console.WriteLine("Too many fails. Bail!");
         Console.ReadLine();
         return;
      }
   }
}

And this is the Visual Basic version. Note the When keyword after the Catch keyword:

'Do something 10 times, bail after 3 errors.
For X As Integer = 0 To 9
   Try
      Console.WriteLine("Try something.")
      'This operation will fail.
      Throw New Exception()
   Catch ex As Exception When X < 3
      Console.WriteLine("Failed!")
   Catch ex As Exception
      Console.WriteLine("Too many fails. Bail!")
      Return
   End Try
Next

The way it should be.

Categories: Visual Studio 10.

Visual Basic: The most excellent code editor

I can’t hide the fact that I have a childish love for Visual Basic. I think this is worth a few blog posts. Than language and the code editor together works so incredible well for me. The language provides code blocks with keywords for opening and closing, so that you can read out what kind of block is closing. Because of this, the code editor knows about your intentions. Also, the C# editor cannot know if you intend to use curly brackets or not, because they are optional if only one statement will be contained within a block. In C#, to do an iteration with a test in, the iteration and its brackets has to be typed out, and then the test and its brackets has to be typed out.

In Visual Basic, I just write the iteration opening, and when hitting Enter, the editor closes my iteration, does the indentation and places the cursor within, so that I can continue writing my test. Again, I just write the opening part of the test and hit Enter, and the editor closes it, does the indentation and place my cursor within the new block.

for (int a = 0; a <= 10; a++)
{
   if (true)
   {
      //Alcatraz style
   }
}

For A As Integer = 0 To 10
  If True Then
     'Quick and nice!
  End If
Next

Also, what } actually means, might depend. Yes, it is a closing block, but what block? In Visual Basic, the block closers are nice and readable. Next is closing For, End While is a closing While, End If is a closing If, and so on.

Categories: Visual Studio 10.

My bits on evolution, part 6

Some of my bits for the Swedish Skeptic Podcast, Skeptikerpodden, on evolution and creationism, in Swedish.

Några av mina bidrag till svenska Skeptikerpodden om evolution och kreationism, på svenska.

16. Kreationistpropaganda från Bibelfokus.se (del 3 av 3) (från Skeptikerpodden 18/1 2011)

17. Information och evolution (från Skeptikerpodden 8/2 2011)

18. Design och förklaringsvärde (från Skeptikerpodden 8/3 2011)

Föregående

Categories: Science.

Tags:

PowerShell knows about your USB devices

One of many things you can do with the Management assembly is to get the USB devices that is currently connected to your computer. To load the Management assembly, use this line of code (no line break here):

[System.Reflection.Assembly]::Load("System.Management, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

The class you want to create an instance from is called ManagementClass, and to its constructor you pass the management path that you want to use. USB devices are located in the Win32_USBHub path, so that is the argument that I pass to the constructor.

$Man = New-Object System.Management.ManagementClass("Win32_USBHub")

The GetInstances function returns a collection of objects, each object representing a device that actually is connected. Just for being crazy, I will make my target variable type safe.

[System.Management.ManagementObjectCollection]$Devs = $Man.GetInstances()

Now I can use ForEach-Obect cmdlet to iterate through the collection. For each device, I will write out the name of the device, the system ID and a blank line.

$Devs | ForEach-Object {
	Write-Output $_.GetPropertyValue("Name").ToString()
	Write-Output $_.GetPropertyValue("DeviceID").ToString()
	Write-Output ""
}

Finally, I have to free the resouces I have used.

$Devs.Dispose()
$Man.Dispose()

When you run this code, you should see a list of devices that is registered as connected to your machine, including the USB hubs. If you connect a device and run the script again, that device will show up in the list. With this code as base, you could easily write programs that detects changes to the list. That is, programs that detects when a new device is added or removed. The last item should be the device you inserted while your computer was running, and the first items are the devices that were available at system startup.

Categories: PowerShell.

Tags:

Adding references to custom types

In a great number of blog posts, I have used the Load function of System.Reflection.Assembly to load types from the .NET Framework. This (without line break) is an example that gives you access to the Forms library…

[System.Reflection.Assembly]::Load("System.Windows.Forms, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089")

…so that calls like this is possible:

[System.Windows.Forms.MessageBox]::Show("Hello!")

(To see the available assemblies, check the assembly folder in your Windows folder.)

When you use the Add-Type cmdlet to create your own types, the string that describes the type might need references as well. The required assemblies are specified in an array, and passed to the cmdlet as the -ReferencedAssemblies argument. This code adds a custom type…

$references = @("System.Windows.Forms")
Add-Type -ReferencedAssemblies $references @'
public class Test
{
   public void hej()
   {
      System.Windows.Forms.MessageBox.Show("Hello!");
   }
}
'@

…gives you a code that when invoked, does the same thing:

$test = New-Object Test
$test.hej()

The problem will show up if you have made any changes to your type and run your program again. The type called Test will already be loaded, so the Add-Type cmdlet will fail.

(If you run your program again, without changing your custom type definition, Add-Type will just be ignored – your type is there and everything is fine.)

Since types cannot be unloaded, you will need to unload your entire appdomain, and the easiest way to do this, is to close your PowerShell window. So any changes to a custom type, will be reflected in a new instance of PowerShell, thus in a new appdomain.

Categories: PowerShell.

Environment variables

Assuming that you are running Windows 7, the environment variables can be manually accessed if you right click on Computer, and select Properties. From there, you click Advanced system settings and on the Advanced tab, you click the Environment variables button. You can check your current variables, edit them and add new variables.

I am running a Swedish installation of Windows 7.

To read them from Visual Basic, you just use the GetEnvironmentVariables function to retrieve the collection of registered variables. This example is written in VBx (Visual Basic 10):

Console.WriteLine(
   Environment.GetEnvironmentVariables().
      Item("PROCESSOR_REVISION").ToString())

Remember, when you write code to manipulate this collection, adding or changing values, you would normally want your code to run as a custom step in an MSI file, and not in a regular EXE.

Categories: Visual Basic 10.

Visit ACNE, view source

Visit http://www.acnestudios.com/ and view the source of their web page. There you have a small challenge for a web developer.

Thanks for the tip, Staffan!

Categories: Geeky.

Calling C functions

Like I mentioned earlier, functions that only are exposed through an external .NET interface are unreachable from PowerShell, but can be called using reflection. But how about C functions?

This is not a problem at all. Like always when you attempt to call a C function in a DLL, you must know how it is exposed. This is not unique for PowerShell. The name of the link library, the name of the entry point, and the parameter types. This gives you a huge number of functionality ready to call, including third party libraries and the Windows API.

I am going to use PowerShell to move the mouse cursor to location 100, 100 (left, top). The SetCursorPos function takes two integer values (X and Y) and returns a boolean. According to the Windows API documentation, the function resides in a library called User32.dll.

One way to do this, is to write Visual Basic code, use PowerShell to compile it to an assembly, and then use reflection to call it. But there is another way.

Create one array of arguments, and an array of argument types. In my case, since I’m calling the SetCursorPos function, this is what I need:

$parameterTypes = [UInt32], [UInt32]
$parameters = 100, 100

Then, the rest of the code is something written by Jouko Kynsijärvi, that Lee Holmes used to make the Invoke-Win32 function. This is my complete code. Three lines! Check this out!

#The parameter types.
$parameterTypes = [Int], [Int]

#The arguments.
$parameters = 100, 100

#The call. Library, return type, function name, types and values.
Invoke-Win32 "User32.dll" ([Bool]) "SetCursorPos" $parameterTypes $parameters

The rest of the listing is the definition of the Invoke-Win32 function that I extracted from this Lee Holmes’ post.

As you run this script, note how the mouse cursor jumps up to the upper left corner, 100 pixels from the left edge, 100 pixels from the top.

(I have a huge smile across my face when I’m writing this.)

Categories: PowerShell.

Tags: