I want to see if there is a way to store a single value in one column in a database, but when read it could be interpreted as four columns in a database.
I have square, which has four sides. I would like to store a value that tells me what sides should have a dashed line. When this value is read I can easily decipher like the left and right side should be dashed, or just the top side, or all sides, or none.
I know I could have say 17 options I could store, but is there an easier way with a number? I will have four buttons in the interface showing which sides they want dotted and will store a value that way.
Is there a way to show me this in some pseudo-code in the storing and reinterpreting parts?
There are 16 possibilities for the sides--each side has two possibilities, and each decision is independent from the others, so you multiply the numbers together, getting 2*2*2*2=16
.
You could just store an integer between 0
and 15
. To get the choice for the left side, calculate n & 1
where n
is the stored number. (The "&" symbol means "bitwise and" in many computer languages.) The result 1
means dashed, while 0
means solid. To get the right side, calculate n & 2
, the top is n & 4
, while the bottom is n & 8
. Note that the "magic numbers" in those formulas are 2**0
, 2**1
, 2**2
, and 2**3
.
You can easily go the other way. If your choices expressed as 0
or 1
are a,b,c,d
, then n = 1*a + 2*b + 4*c + 8*d
. Note the same magic numbers as in the previous paragraph.
If you know the binary number system, those formulas are obvious. If you want to learn more, do a web search on "binary number".
Of course, another way to solve your problem is to store a string value rather than an integer. For example, you could store
"left=dashed, right=solid, top=solid, bottom=dashed"
and use the string-handling facilities of your language to parse the string. This is a more lengthy process than my first method, and uses more memory for the storage, but it has the advantage of being more transparent and easy to understand for anyone examining the data.
Your idea in a comment of using a short string like "1101"
is a good one, and depending on the implementation it may even use less memory than my first solution. It shows the same amount of information as my first solution and less than my second. The implementation of your idea and the others depends on the language and on how you store the decision for each side in a variable. In Python, if n
is the stored (string) value and the decisions for each side are Boolean variables a,b,c,d
(True
means dashed, False
means solid), your code could be
a = (n[0] == '1')
b = (n[1] == '1')
c = (n[2] == '1')
d = (n[3] == '1')
There are shorter ways to do this in Python but they are less understandable to non-Python programmers.