java-org.hwo/src/org/hwo/bitfields/BitField.java

100 lines
1.9 KiB
Java
Raw Normal View History

2014-07-25 00:29:44 +02:00
package org.hwo.bitfields;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class BitField {
private Integer value;
private List<Field> fields;
public BitField()
{
this.fields = new ArrayList<Field>();
initialize();
}
public BitField(Element fieldsNode)
{
this.fields = new ArrayList<Field>();
NodeList fields = fieldsNode.getElementsByTagName("Field");
for (int i=0;i<fields.getLength();i++)
{
Element fieldNode = (Element)fields.item(i);
int start = 0,
len = 1;
if (fieldNode.getAttribute("len") != null)
len = Integer.decode(fieldNode.getAttribute("len"));
if (fieldNode.getAttribute("start") != null)
start = Integer.decode(fieldNode.getAttribute("start"));
this.fields.add(new Field(this,start,len,fieldNode.getTextContent()));
}
}
private void initialize()
{
for (int i=0;i<32;i++)
this.fields.add(new Field(this, i, 1));
}
public synchronized String toText(int value)
{
this.value = value;
return toText();
}
public synchronized String toText()
{
StringBuilder sb = new StringBuilder();
if (value != null)
{
for (Field field:this.fields)
{
String st = field.toText();
if (st != null)
{
if (sb.length() > 0)
sb.append(", ");
sb.append(st);
}
}
}
return sb.toString();
}
public synchronized Integer getValue()
{
return this.value;
}
public synchronized void setValue(Integer value)
{
this.value = value;
}
public synchronized int getValue(int start,int len)
{
if (value == null)
return 0;
return (value >> start) & (-1 >> (Integer.SIZE - len));
}
public synchronized void setValue(int value,int start,int len)
{
if (this.value == null)
this.value = 0;
this.value &= ~((-1 >> (Integer.SIZE - len)) << start);
this.value |= (value & (-1 >> (Integer.SIZE - len))) << start;
}
}