working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,757 snippets matching: binary

    public by Geometry modified Aug 7, 2016  75895  0  4  0

    Load P6 PPM image (color PNM image with binary encoding)

    Load P6 PPM image (color PNM image with binary encoding)
    // Load P6 PPM image (color PNM image with binary encoding)
    private static unsafe Bitmap ReadP6Image(Stream stream, int width, int height, int maxValue)
    {
        double scalingFactor = (double)255 / maxValue;
    
        // create new bitmap and lock it
        Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        BitmapData imageData = image.LockBits(new Rectangle(0, 0, width, height),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    
        int stride = imageData.Stride;
        byte* ptr = (byte*)imageData.Scan0.ToPointer();
    
        // prepare a buffer for one line
        int lineSize = width * 3;
        byte[] line = new byte[lineSize];
    
        int totalBytesRead = 0, bytesRead = 0;
    
        // load all rows
        for (int y = 0; y < height; y++)
        {
            totalBytesRead = 0;
            bytesRead = 0;
    
            // load next line
            while (totalBytesRead != lineSize)
            {
                bytesRead = stream.Read(line, totalBytesRead, lineSize - totalBytesRead);
    
                if (bytesRead == 0)
                {
                    // if we've reached the end before complete image is loaded, then there should
                    // be something wrong
                    throw new InvalidOperationException("Execution should not reach here.");
                }
    
                totalBytesRead += bytesRead;
            }
    
            // fill next image row
            byte* row = ptr + stride * y;
    
            for (int x = 0, i = 0; x < width; x++, i += 3, row += 3)
            {
                row[2] = (byte)(scalingFactor * line[i]);       // red
                row[1] = (byte)(scalingFactor * line[i + 1]);   // green
                row[0] = (byte)(scalingFactor * line[i + 2]);   // blue
            }
        }
    
        // unlock image and return it
        image.UnlockBits(imageData);
        return image;
    }

    public by cghersi modified Jan 21, 2014  2820  1  7  1

    Save binary file in Java

    this is the simplest method to save a binary content onto a file in Java
    public static void saveToFile(String completeFileName, byte[] data) throws IOException {
        FileOutputStream out = new FileOutputStream(completeFileName);
        out.write(data);
        out.flush();
        out.close();
    }

    public by Geometry modified Jul 31, 2016  830  0  4  0

    FromFloatingPointBinaryString: Parses a floating point binary string into a double.

    Parses a floating point binary string into a double.
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Parses a floating point binary string into a double.
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static double FromFloatingPointBinaryString(string s)
    {
        double sign;
        double val = 0.0;
    
        var binRegex = "(?<Sign>[+-]?)(?<Whole>[01]+).?(?<Fraction>[01]*)";
        var match = Regex.Match(s, binRegex);
    
        if (!match.Success) throw new ArgumentException("s");
                
        sign = match.Groups["Sign"].Value == "-" ? -1.0 : 1.0;
        if (match.Groups["Fraction"].Success)
        {
            var fraction = match.Groups["Fraction"].Value;
            for (int i = 0; i < fraction.Length; i++)
            {
                if (fraction[i] == '1')
                {
                    val += Math.Pow(2.0, -i-1);
                }
            }
        }
        var whole = match.Groups["Whole"].Value;
        for (int i = 0; i < whole.Length; i++)
        {
            if (whole[whole.Length - i - 1] == '1')
            {
                val += Math.Pow(2.0, i);
            }
        }
        return sign * val;
    }

    public by Geometry modified Aug 7, 2016  782  0  4  0

    Load P5 PGM image (grayscale PNM image with binary encoding)

    Load P5 PGM image (grayscale PNM image with binary encoding)
    // Load P5 PGM image (grayscale PNM image with binary encoding)
    private static unsafe Bitmap ReadP5Image(Stream stream, int width, int height, int maxValue)
    {
        double scalingFactor = (double)255 / maxValue;
    
        // create new bitmap and lock it
        Bitmap image = Tools.CreateGrayscaleImage(width, height);
        BitmapData imageData = image.LockBits(new Rectangle(0, 0, width, height),
            ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
    
        int stride = imageData.Stride;
        byte* ptr = (byte*)imageData.Scan0.ToPointer();
    
        // prepare a buffer for one line
        byte[] line = new byte[width];
    
        int totalBytesRead = 0, bytesRead = 0;
    
        // load all rows
        for (int y = 0; y < height; y++)
        {
            totalBytesRead = 0;
            bytesRead = 0;
    
            // load next line
            while (totalBytesRead != width)
            {
                bytesRead = stream.Read(line, totalBytesRead, width - totalBytesRead);
    
                if (bytesRead == 0)
                {
                    // if we've reached the end before complete image is loaded, then there should
                    // be something wrong
                    throw new InvalidOperationException("Execution should not reach here.");
                }
    
                totalBytesRead += bytesRead;
            }
    
            // fill next image row
            byte* row = ptr + stride * y;
    
            for (int x = 0; x < width; x++, row++)
            {
                *row = (byte)(scalingFactor * line[x]);
            }
        }
    
        // unlock image and return it
        image.UnlockBits(imageData);
        return image;
    }

    public by Geometry modified Jul 31, 2016  758  0  4  0

    ToFloatingPointBinaryString: Formats a double as a floating point binary string, e.g. 0.25 -> 0.01

    Formats a double as a floating point binary string, e.g. 0.25 - 0.01 4 = 1.2^2 - 100 0.25 = 1.2^-2 - 0.01
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Formats a double as a floating point binary string, e.g. 0.25 -> 0.01
    /// </summary>
    /// <param name="d"></param>
    /// <returns></returns>
    /// <example>4    = 1.2^2    -> 100
    /// 0.25 = 1.2^-2   -> 0.01
    /// </example>
    public static string ToFloatingPointBinaryString(this double d)
    {
        var dc = new DoubleComponents(d);
        dc.MaximizeExponent();
    
        var revChars = new List<char>();
    
        while (dc.Exponent < 0)
        {
            revChars.Add(((dc.Mantissa & 1L) == 1L) ? '1' : '0');
            dc.Exponent++;
            dc.Mantissa >>= 1;
        }
        revChars.Add('.');
        // Write out 0s as long as the exponent suggests
        while (dc.Exponent > 0)
        {
            revChars.Add('0');
            dc.Exponent--;
        }
        // write out the rest of the Mantissa
        while (dc.Mantissa != 0L)
        {
            revChars.Add( ((dc.Mantissa & 1L) == 1L) ? '1' : '0');
            dc.Mantissa >>= 1;
        }
                
        // Before we reverse - add a '0' to the end (which will go in front) if needed
        if (revChars.Last() == '.') revChars.Add('0');
                
        // Prepend the sign (by adding before we reverse)
        if (dc.Negative) revChars.Add('-');
        revChars.Reverse();
                
        // Now a '0' after the '.' if needed (alternative would be to strip to '.')
        if (revChars.Last() == '.') revChars.Add('0');
    
        return new string(revChars.ToArray());
    }

    public by rioxshen modified May 2, 2014  2237  1  5  0

    [leetcode] Convert Sorted Array to Binary Search Tree

    #!/usr/bin/env python
    
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def convert_array_bst(self, num):
            """ Converts a sorted array to a binary search tree.
    
            Approach:
            1. Utilizes BST definition - the left node is no greater than
            the root and right is no less than the root, 
            so the root should be the middle element in the array,
            left child should be the mid of left half and so on.
            2. Divide and Conquer is handfy for repeated pattern.
            """
            if not num:
                return None
    
            return self.build(num, 0, len(num)-1)
    
        def build(self, num, start, end):
            if start > end:
                return None
    
            mid = (start+end) / 2
            node = TreeNode(num[mid])
            node.left = self.build(num, start, mid-1)
            node.right = self.build(num, mid+1, end)
    
            return node
    

    public by afelicioni modified Feb 12, 2016  2274  0  3  0

    legacy binary node ubuntu issue fix

    legacy binary node ubuntu issue fix: gistfile1.txt
    sudo apt-get install nodejs-legacy
    
    

    public by Genaro Madrid modified Feb 3, 2015  1700  0  3  0

    Binary & hex conversion functions

    Binary & hex conversion functions: bin_hex_functions
    def bin_to_hex(s)
      s.scrub.unpack('H*').first
    end
    
    def hex_to_bin(s)
      s.scan(/../).map { |x| x.hex }.pack('c*')
    end
    
    
    

    public by troy modified Sep 25, 2019  40  1  4  1

    How can I get an image from raw binary pixel content?

    Given a raw binary content, this gives me a stream that can be easily turned into an Image
    public static async Task<InMemoryRandomAccessStream> ImageFromBytes(this byte[] imagePixels, int width, int dpi, Rect frame)
    {
    	//BitmapImage bitmap = new BitmapImage();
    	int xStart = (int)frame.X;
    	int yStart = (int)frame.Y;
    	int frameWidth = (int)frame.Width;
    	int frameHeight = (int)frame.Height;
    	byte[] framePixels = new byte[4 * frameWidth * frameHeight];
    	for (int y = 0; y < frameHeight; y++)
    	{
    		for (int x = 0; x < frameWidth; x++)
    		{
    			int frameOffset = (4 * y * frameWidth) + (4 * x);
    			int imageOffset = (4 * (y + yStart) * width) + (4 * (x + xStart));
    			framePixels[frameOffset] = imagePixels[imageOffset];
    			framePixels[frameOffset + 1] = imagePixels[imageOffset + 1];
    			framePixels[frameOffset + 2] = imagePixels[imageOffset + 2];
    			framePixels[frameOffset + 3] = imagePixels[imageOffset + 3];
    		}
    	}
    
    	InMemoryRandomAccessStream bitmapStream = new InMemoryRandomAccessStream();
    	BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, bitmapStream);
    	encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)frameWidth, (uint)frameHeight, dpi, dpi, framePixels);
    
    	try
    	{
    		await encoder.FlushAsync();
    	}
    	catch
    	{
    		return bitmapStream;
    	}
    
    	return bitmapStream;
    }				

    public by guantalamo56 modified Sep 25, 2019  36  0  4  0

    UWP: turn byte array into image

    Given a byte array, let's turn it into an Image that can be used in UWP UI contexts.
    public static async Task<Image> ToImage(this byte[] input)
    {
    	if (input == null)
    		return null;
    	BitmapImage biSource = new BitmapImage();
    	using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
    	{
    		await stream.WriteAsync(input.AsBuffer());
    		stream.Seek(0);
    		await biSource.SetSourceAsync(stream);
    	}
    
    	return new Image { Source = biSource };
    }					
    • Public Snippets
    • Channels Snippets