001    /*
002     * This file is part of muCommander, http://www.mucommander.com
003     * Copyright (C) 2002-2008 Maxence Bernard
004     *
005     * muCommander is free software; you can redistribute it and/or modify
006     * it under the terms of the GNU General Public License as published by
007     * the Free Software Foundation; either version 3 of the License, or
008     * (at your option) any later version.
009     *
010     * muCommander is distributed in the hope that it will be useful,
011     * but WITHOUT ANY WARRANTY; without even the implied warranty of
012     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013     * GNU General Public License for more details.
014     *
015     * You should have received a copy of the GNU General Public License
016     * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017     */
018    
019    package com.mucommander.io;
020    
021    /**
022     * This class provides convenience static methods that operate on bits and bytes.
023     *
024     * @author Maxence Bernard
025     */
026    public class ByteUtils {
027    
028        /**
029         * Sets/unsets a bit in the given integer.
030         *
031         * @param i the permission int
032         * @param bit the bit to set
033         * @param enabled true to enable the bit, false to disable it
034         * @return the modified permission int
035         */
036        public static int setBit(int i, int bit, boolean enabled) {
037            if(enabled)
038                i |= bit;
039            else
040                i &= ~bit;
041    
042            return i;
043        }
044    
045        /**
046         * Returns an hexadecimal string representation of the given byte array, where each byte is represented by two
047         * hexadecimal characters and padded with a zero if its value is comprised between 0 and 15 (inclusive).
048         * As an example, this method will return "6d75636f0a" when called with the byte array {109, 117, 99, 111, 10}.
049         *
050         * @param bytes the array of bytes for which to get an hexadecimal string representation
051         * @return an hexadecimal string representation of the given byte array
052         */
053        public static String toHexString(byte bytes[]) {
054            StringBuffer sb = new StringBuffer();
055    
056            int bytesLen = bytes.length;
057            String hexByte;
058            for(int i=0; i<bytesLen; i++) {
059                hexByte = Integer.toHexString(bytes[i] & 0xFF);
060                if(hexByte.length()==1)
061                    sb.append('0');
062                sb.append(hexByte);
063            }
064    
065            return sb.toString();
066        }
067    }