tags:

views:

98

answers:

3

I'm programming a microcontroller in C and as part of it want to display certain letters on a 7 segment display. Each letter has a corresponding number that makes the 7 segment display show the letter. There's no real pattern to it cause the number is just made by adding up the bits on the 7 segment display that are needed to show the letter so it'd be really nice if I could create some sort of dictionary to do this.

If I was using C# or something I'd just make a dictionary and then add the letters as keys and the numbers as values but as far as I know I can't do this in C. Is there another way to do it or do should I just write a function like int displayletter(char letter) that uses a bunch of if statements to return the right numbers?

Sorry if it's a stupid question, I'm quite new to C.

A: 

If you want a dictionary in C i recored using the Judy library.

However the idea of a dictionary isn't very c-like. Ideally you can use an array or linked list of structs. Then iterate though it to find the value based on a key. This is fundamentally what a dictionary is doing. so you can declare a struct like this:

struct word_lookup{
char  key;
word c;
};

Although even this approach is still wasteful. Often times when dealing with words you would use a bitwise operator to covert it into an ascii character.

Rook
+3  A: 

You could create an array

 int values[26];

and populate it with the values for each letter, however they're calculated

Then create a function that takes a character and returns an int

int GetValueFromChar(char c)
{
    return values[c - 'A'];
}

This is simplistic, as it assumes you'll only use upper case letters in an ASCII character set, but you should get the idea.

Matt Ellen
What if the computer is using the EBCDIC character set and not ASCII?
Swiss
Unless you're IBM in 1975, it's not going to be EBCDIC.
Greg Hewgill
@Swiss: that's a good point. I am assuming an ASCII character set, but the underlying mechanism should be the same. I've updated the answer to reflect that assumption.
Matt Ellen
@Matt Ellen: Characters in EBCDIC aren't continuous - they're broken into chunks. You might want to use 'A' instead of 65 to make this a little more portable and readable though.
Swiss
@Swiss: good thinking!
Matt Ellen
will return values[c-'0']; work in EBCDIC??
@Greg Hewgill: From what I've heard, z/OS still uses EBCDIC as its primary character set.
Swiss
EBCDIC is still _heavily_ used. Just the one (System z) platform but it's _everywhere_.
paxdiablo
On a *microcontroller*?
Greg Hewgill
Thanks, great idea. Totally forgot that ASCII characters are just considered to be numbers but that should work great. :)
Sam
A: 

Easiest would be to just use a function and a switch statement... I believe for this purpose the switch statement would be very efficient. I also second the Judy library as a good one to use for efficient mapping, but it's kind of overkill for this.