Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Bitwise Operation: Quickly Convert Binary Bit to Integer and vice versa using Javascript Shell

using JavaScript shell found at www.squarefree.com/shell/ , it's very easy to convert binary bit to integer and vice versa

convert integer to binary bit string
num = 1024
num.toString(2)


convert binary bit string to integer
parseInt('111', 2)

nsieve for Ruby


From: The Great Computer Language Shootout: nsieve-bits Ruby
Author: Glenn Parker


CharExponent = 3
BitsPerChar = 1 << CharExponent
LowMask = BitsPerChar - 1

def sieve(m)
  ret = []
  items = "\xFF" * ((m / BitsPerChar) + 1)
  masks = ""
  BitsPerChar.times do |b|
    masks << (1 << b).chr
  end

  count = 0
  pmax = m - 1
  2.step(pmax, 1) do |p|
    if items[p >> CharExponent][p & LowMask] == 1
      ret << p
      count += 1
      p.step(pmax, p) do |mult|
	a = mult >> CharExponent
	b = mult & LowMask
	items[a] -= masks[b] if items[a][b] != 0
        #p items
      end
    end
  end
  #count
  ret
end

n = (ARGV[0] || 2).to_i
n.step(n - 2, -1) do |exponent|
  break if exponent < 0
  m = 2 ** exponent * 10_000
  primes = sieve(m)
  count = primes.size
  puts
  printf "Primes up to %8d %8d\n", m, count
  puts "last ten primes: #{primes[-10..-1].join(' ')}"
  puts
end


Convert a long to HEX value and the other way around

Handy to convert MD5 or SHA-1 hash values.

	public static long hexToLong(byte[] bytes) {

		if (bytes.length > 16) {
			throw new IllegalArgumentException("Byte array too long (max 16 elements)");
		}
		long v = 0;
		for (int i = 0; i < bytes.length; i += 2) {
			byte b1 = (byte) (bytes[i] & 0xFF);

			b1 -= 48;
			if (b1 > 9) b1 -= 39;

			if (b1 < 0 || b1 > 15) {
				throw new IllegalArgumentException("Illegal hex value: " + bytes[i]);
			}

			b1 <<=4;

			byte b2 = (byte) (bytes[i + 1] & 0xFF);
			b2 -= 48;
			if (b2 > 9) b2 -= 39;

			if (b2 < 0 || b2 > 15) {
				throw new IllegalArgumentException("Illegal hex value: " + bytes[i + 1]);
			}

			v |= (((b1 & 0xF0) | (b2 & 0x0F))) & 0x00000000000000FFL ;

			if (i + 2 < bytes.length) v <<= 8;
		}

		return v;
	}

	public static byte[] longToHex(final long l) {
		long v = l & 0xFFFFFFFFFFFFFFFFL;

		byte[] result = new byte[16];
		Arrays.fill(result, 0, result.length, (byte)0);

		for (int i = 0; i < result.length; i += 2) {
			byte b = (byte) ((v & 0xFF00000000000000L) >> 56);

			byte b2 = (byte) (b & 0x0F);
			byte b1 = (byte) ((b >> 4) & 0x0F);

			if (b1 > 9) b1 += 39;
			b1 += 48;

			if (b2 > 9) b2 += 39;
			b2 += 48;

			result[i] = (byte) (b1 & 0xFF);
			result[i + 1] = (byte) (b2 & 0xFF);

			v <<= 8;
		}

		return result;
	}



And tests:

	public void testHexToLong() throws Exception {
		assertEquals(-7057002501900618110L, NumberUtils.hexToLong("9e107d9d372bb682".getBytes()));
		assertEquals(-10908158098650842L, NumberUtils.hexToLong("ffd93f1687604926".getBytes()));
	}

	public void testLongToHex() throws Exception {
		assertEquals("9e107d9d372bb682", new String(NumberUtils.longToHex(-7057002501900618110L)));
		assertEquals("ffd93f1687604926", new String(NumberUtils.longToHex(-10908158098650842L)));
	}

BitField: A fast(ish), pure Ruby bit field "type"

#        NAME: BitField
#      AUTHOR: Peter Cooper
#     LICENSE: MIT ( http://www.opensource.org/licenses/mit-license.php )
#   COPYRIGHT: (c) 2007 Peter Cooper (http://www.petercooper.co.uk/)
#     VERSION: v4
#     HISTORY: v4 (fixed bug where setting 0 bits to 0 caused a set to 1)
#              v3 (supports dynamic bitwidths for array elements.. now doing 32 bit widths default)
#              v2 (now uses 1 << y, rather than 2 ** y .. it's 21.8 times faster!)
#              v1 (first release)
#
# DESCRIPTION: Basic, pure Ruby bit field. Pretty fast (for what it is) and memory efficient.
#              I've written a pretty intensive test suite for it and it passes great. 
#              Works well for Bloom filters (the reason I wrote it).
#
#              Create a bit field 1000 bits wide
#                bf = BitField.new(1000)
#
#              Setting and reading bits
#                bf[100] = 1
#                bf[100]    .. => 1
#                bf[100] = 0
#
#              More
#                bf.to_s = "10101000101010101"  (example)
#                bf.total_set         .. => 10  (example - 10 bits are set to "1")

class BitField
  attr_reader :size
  include Enumerable
  
  ELEMENT_WIDTH = 32
  
  def initialize(size)
    @size = size
    @field = Array.new(((size - 1) / ELEMENT_WIDTH) + 1, 0)
  end
  
  # Set a bit (1/0)
  def []=(position, value)
    if value == 1
      @field[position / ELEMENT_WIDTH] |= 1 << (position % ELEMENT_WIDTH)
    elsif (@field[position / ELEMENT_WIDTH]) & (1 << (position % ELEMENT_WIDTH)) != 0
      @field[position / ELEMENT_WIDTH] ^= 1 << (position % ELEMENT_WIDTH)
    end
  end
  
  # Read a bit (1/0)
  def [](position)
    @field[position / ELEMENT_WIDTH] & 1 << (position % ELEMENT_WIDTH) > 0 ? 1 : 0
  end
  
  # Iterate over each bit
  def each(&block)
    @size.times { |position| yield self[position] }
  end
  
  # Returns the field as a string like "0101010100111100," etc.
  def to_s
    inject("") { |a, b| a + b.to_s }
  end
  
  # Returns the total number of bits that are set
  # (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
  def total_set
    @field.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
  end
end


Here's the tests if you want to run:

require "test/unit"
require "bitfield"

class TestLibraryFileName < Test::Unit::TestCase
  def setup
    @public_bf = BitField.new(1000)
  end
  
  def test_basic
    assert_equal 0, BitField.new(100)[0]
    assert_equal 0, BitField.new(100)[1]
  end
  
  def test_setting_and_unsetting
    @public_bf[100] = 1
    assert_equal 1, @public_bf[100]
    @public_bf[100] = 0
    assert_equal 0, @public_bf[100]
  end

  def test_random_setting_and_unsetting
    100.times do
      index = rand(1000)
      @public_bf[index] = 1
      assert_equal 1, @public_bf[index]
      @public_bf[index] = 0
      assert_equal 0, @public_bf[index]
    end
  end
  
  def test_multiple_setting
    1.upto(999) do |pos|
      2.times { @public_bf[pos] = 1 }
      assert_equal 1, @public_bf[pos]
    end
  end

  def test_multiple_unsetting
    1.upto(999) do |pos|
      2.times { @public_bf[pos] = 0 }
      assert_equal 0, @public_bf[pos]
    end
  end
  
  def test_size
    assert_equal 1000, @public_bf.size
  end
  
  def test_to_s
    bf = BitField.new(10)
    bf[1] = 1
    bf[5] = 1
    assert_equal "0100010000", bf.to_s
  end
  
  def test_total_set
    bf = BitField.new(10)
    bf[1] = 1
    bf[5] = 1
    assert_equal 2, bf.total_set
  end
end

Java - showBitPlanes

// the input it must be a b/w image

public BufferedImage showBitPlanes(BufferedImage bi, int lv)
	{
		int level = 0;
		
		switch(level)
		{
			case 0:
				level = 128;
				break;
			case 1:
				level = 64;
				break;
			case 2:
				level = 32;
				break;
			case 3:
				level = 16;
				break;
			case 4:
				level = 8;
				break;
			case 5:
				level = 4;
				break;
			case 6:
				level = 2;
				break;
			case 7:
				level = 1;
				break;
			default:
					return null;
		}
		
		int width = bi.getWidth();
		int height = bi.getHeight();
		
		BufferedImage img = new BufferedImage(width, height, bi.getType());
		
		for(int x=0; x<width; x++)
			for(int y=0; y<height; y++)
				img.setRGB(x, y, ((bi.getRGB(x, y) & level)/level)*255);
		
		return img;
	}

Matlab - showBitPlanes

% Ritorna i Bit Plabes dell'immagine a toni di grigio

function showBitPlanes(img)

    imgGray = double( rgb2gray(img) );
    titleString = 'bit planes ';
    
    % MSB ... LSB
    k = 128;
    
    for b=1:8
        
        subplot(2, 4, b);
        imshow( (bitand(imgGray, k) / k) * 255 ); % Fa un and dei bit
        title([titleString int2str(b-1)]);
        k = k/2; % Shifta di 2 i bit
        
    end;
    
return;

Simple bit operations //Pascal functions

Get, Clear, Set and Enable bit operations for pascal.

function GetBit(const Value: DWord; const Bit: Byte): Boolean;
begin
  Result := (Value and (1 shl Bit)) <> 0;
end;

function ClearBit(const Value: DWord; const Bit: Byte): DWord;
begin
	Result := Value and not (1 shl Bit);
end;

function SetBit(const Value: DWord; const Bit: Byte): DWord;
begin
	Result := Value or (1 shl Bit);
end;

function EnableBit(const Value: DWord; const Bit: Byte; const TurnOn: Boolean): DWord;
begin
	Result := (Value or (1 shl Bit)) xor (Integer(not TurnOn) shl Bit);
end;
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS