1 /*
2  * @(#) $Id: ASN1BitString.java,v 1.4 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10package org.jstk.asn1;
11
12public class ASN1BitString extends ASN1Type {
13    public ASN1BitString(){
14        super(UNIVERSAL, NONE, BIT_STRING, BIT_STRING);
15    }
16    public ASN1BitString(byte tagClass, int taggingMethod, int tagNumber){
17            super(tagClass, taggingMethod, tagNumber, BIT_STRING);
18    }
19    public String toString(){
20        if (value == null)
21            return "ASN1BitString: null";
22
23        StringBuffer sb = new StringBuffer();
24        int noUnusedBits = value[0];
25        for (int i = 1; i < value.length; i++){
26            byte cbyte = value[i];
27            for (int j = 0; j < 8; j++){
28                if ((cbyte & 0x80) == 0x80)
29                    sb.append("1");
30                else
31                    sb.append("0");
32                cbyte = (byte)(cbyte << 1);
33                if ((i == value.length - 1) && (j + noUnusedBits == 8 - 1))
34                    break;
35            }
36        }
37        return "ASN1BitString: " + sb.toString();
38    }
39
40    public byte[] getValue(){
41        if (this.length < 1)
42            return null;
43        byte[] bytes = new byte[this.length - 1];
44        System.arraycopy(value, 1, bytes, 0, this.length - 1);
45        return bytes;
46    }
47    public void setValue(byte[] value){
48        setValue(value, 0);
49    }
50
51    public void setValue(byte[] value, int noUnusedBits){
52        this.length = (value != null ? value.length + 1: 1);
53        byte[] bytes = new byte[this.length];
54        bytes[0] = (byte)noUnusedBits;
55        System.arraycopy(value, 0, bytes, 1, this.length - 1);
56        this.value = bytes;
57    }
58    public static void main(String[] args){
59        byte[] bytes = { (byte)0xf1, 0x01 };
60        ASN1BitString bs = new ASN1BitString();
61        bs.setValue(bytes);
62        System.out.println(bs.toString());
63    }
64}