左移 右移 与 或-关于左移右移与或的作用

问题描述

关于左移右移与或的作用
希望 有耐心的大牛给解惑


public class DiskBasedCache implements Cache {

/** Map of the Key CacheHeader pairs */private final Map<String CacheHeader> mEntries =        new LinkedHashMap<String CacheHeader>(16 .75f true);/** Total amount of space currently used by the cache in bytes. */private long mTotalSize = 0;/** The root directory to use for the cache. */private final File mRootDirectory;/** The maximum size of the cache in bytes. */private final int mMaxCacheSizeInBytes;/** Default maximum disk usage in bytes. */private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024;/** High water mark percentage for the cache */private static final float HYSTERESIS_FACTOR = 0.9f;/** Magic number for current version of cache file format. */private static final int CACHE_MAGIC = 0x20120504;/** * Constructs an instance of the DiskBasedCache at the specified directory. * @param rootDirectory The root directory of the cache. * @param maxCacheSizeInBytes The maximum size of the cache in bytes. */public DiskBasedCache(File rootDirectory int maxCacheSizeInBytes) {    mRootDirectory = rootDirectory;    mMaxCacheSizeInBytes = maxCacheSizeInBytes;}/** * Constructs an instance of the DiskBasedCache at the specified directory using * the default maximum cache size of 5MB. * @param rootDirectory The root directory of the cache. */public DiskBasedCache(File rootDirectory) {    this(rootDirectory DEFAULT_DISK_USAGE_BYTES);}/** * Clears the cache. Deletes all cached files from disk. */@Overridepublic synchronized void clear() {    File[] files = mRootDirectory.listFiles();    if (files != null) {        for (File file : files) {            file.delete();        }    }    mEntries.clear();    mTotalSize = 0;    VolleyLog.d(""Cache cleared."");}/** * Returns the cache entry with the specified key if it exists null otherwise. */@Overridepublic synchronized Entry get(String key) {    CacheHeader entry = mEntries.get(key);    // if the entry does not exist return.    if (entry == null) {        return null;    }    File file = getFileForKey(key);    CountingInputStream cis = null;    try {        cis = new CountingInputStream(new FileInputStream(file));        CacheHeader.readHeader(cis); // eat header        byte[] data = streamToBytes(cis (int) (file.length() - cis.bytesRead));        return entry.toCacheEntry(data);    } catch (IOException e) {        VolleyLog.d(""%s: %s"" file.getAbsolutePath() e.toString());        remove(key);        return null;    } finally {        if (cis != null) {            try {                cis.close();            } catch (IOException ioe) {                return null;            }        }    }}/** * Initializes the DiskBasedCache by scanning for all files currently in the * specified root directory. Creates the root directory if necessary. */@Overridepublic synchronized void initialize() {    if (!mRootDirectory.exists()) {        if (!mRootDirectory.mkdirs()) {            VolleyLog.e(""Unable to create cache dir %s"" mRootDirectory.getAbsolutePath());        }        return;    }    File[] files = mRootDirectory.listFiles();    if (files == null) {        return;    }    for (File file : files) {        FileInputStream fis = null;        try {            fis = new FileInputStream(file);            CacheHeader entry = CacheHeader.readHeader(fis);            entry.size = file.length();            putEntry(entry.key entry);        } catch (IOException e) {            if (file != null) {               file.delete();            }        } finally {            try {                if (fis != null) {                    fis.close();                }            } catch (IOException ignored) { }        }    }}/** * Invalidates an entry in the cache. * @param key Cache key * @param fullExpire True to fully expire the entry false to soft expire */@Overridepublic synchronized void invalidate(String key boolean fullExpire) {    Entry entry = get(key);    if (entry != null) {        entry.softTtl = 0;        if (fullExpire) {            entry.ttl = 0;        }        put(key entry);    }}/** * Puts the entry with the specified key into the cache. */@Overridepublic synchronized void put(String key Entry entry) {    pruneIfNeeded(entry.data.length);    File file = getFileForKey(key);    try {        FileOutputStream fos = new FileOutputStream(file);        CacheHeader e = new CacheHeader(key entry);        e.writeHeader(fos);        fos.write(entry.data);        fos.close();        putEntry(key e);        return;    } catch (IOException e) {    }    boolean deleted = file.delete();    if (!deleted) {        VolleyLog.d(""Could not clean up file %s"" file.getAbsolutePath());    }}/** * Removes the specified key from the cache if it exists. */@Overridepublic synchronized void remove(String key) {    boolean deleted = getFileForKey(key).delete();    removeEntry(key);    if (!deleted) {        VolleyLog.d(""Could not delete cache entry for key=%s filename=%s""                key getFilenameForKey(key));    }}/** * Creates a pseudo-unique filename for the specified cache key. * @param key The key to generate a file name for. * @return A pseudo-unique filename. */private String getFilenameForKey(String key) {    int firstHalfLength = key.length() / 2;    String localFilename = String.valueOf(key.substring(0 firstHalfLength).hashCode());    localFilename += String.valueOf(key.substring(firstHalfLength).hashCode());    return localFilename;}/** * Returns a file object for the given cache key. */public File getFileForKey(String key) {    return new File(mRootDirectory getFilenameForKey(key));}/** * Prunes the cache to fit the amount of bytes specified. * @param neededSpace The amount of bytes we are trying to fit into the cache. */private void pruneIfNeeded(int neededSpace) {    if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {        return;    }    if (VolleyLog.DEBUG) {        VolleyLog.v(""Pruning old cache entries."");    }    long before = mTotalSize;    int prunedFiles = 0;    long startTime = SystemClock.elapsedRealtime();    Iterator<Map.Entry<String CacheHeader>> iterator = mEntries.entrySet().iterator();    while (iterator.hasNext()) {        Map.Entry<String CacheHeader> entry = iterator.next();        CacheHeader e = entry.getValue();        boolean deleted = getFileForKey(e.key).delete();        if (deleted) {            mTotalSize -= e.size;        } else {           VolleyLog.d(""Could not delete cache entry for key=%s filename=%s""                   e.key getFilenameForKey(e.key));        }        iterator.remove();        prunedFiles++;        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {            break;        }    }    if (VolleyLog.DEBUG) {        VolleyLog.v(""pruned %d files %d bytes %d ms""                prunedFiles (mTotalSize - before) SystemClock.elapsedRealtime() - startTime);    }}/** * Puts the entry with the specified key into the cache. * @param key The key to identify the entry by. * @param entry The entry to cache. */private void putEntry(String key CacheHeader entry) {    if (!mEntries.containsKey(key)) {        mTotalSize += entry.size;    } else {        CacheHeader oldEntry = mEntries.get(key);        mTotalSize += (entry.size - oldEntry.size);    }    mEntries.put(key entry);}/** * Removes the entry identified by 'key' from the cache. */private void removeEntry(String key) {    CacheHeader entry = mEntries.get(key);    if (entry != null) {        mTotalSize -= entry.size;        mEntries.remove(key);    }}/** * Reads the contents of an InputStream into a byte[]. * */private static byte[] streamToBytes(InputStream in int length) throws IOException {    byte[] bytes = new byte[length];    int count;    int pos = 0;    while (pos < length && ((count = in.read(bytes pos length - pos)) != -1)) {        pos += count;    }    if (pos != length) {        throw new IOException(""Expected "" + length + "" bytes read "" + pos + "" bytes"");    }    return bytes;}/** * Handles holding onto the cache headers for an entry. */// Visible for testing.static class CacheHeader {    /** The size of the data identified by this CacheHeader. (This is not     * serialized to disk. */    public long size;    /** The key that identifies the cache entry. */    public String key;    /** ETag for cache coherence. */    public String etag;    /** Date of this response as reported by the server. */    public long serverDate;    /** TTL for this record. */    public long ttl;    /** Soft TTL for this record. */    public long softTtl;    /** Headers from the response resulting in this cache entry. */    public Map<String String> responseHeaders;    private CacheHeader() { }    /**     * Instantiates a new CacheHeader object     * @param key The key that identifies the cache entry     * @param entry The cache entry.     */    public CacheHeader(String key Entry entry) {        this.key = key;        this.size = entry.data.length;        this.etag = entry.etag;        this.serverDate = entry.serverDate;        this.ttl = entry.ttl;        this.softTtl = entry.softTtl;        this.responseHeaders = entry.responseHeaders;    }    /**     * Reads the header off of an InputStream and returns a CacheHeader object.     * @param is The InputStream to read from.     * @throws IOException     */    public static CacheHeader readHeader(InputStream is) throws IOException {        CacheHeader entry = new CacheHeader();        int magic = readInt(is);        if (magic != CACHE_MAGIC) {            // don't bother deleting it'll get pruned eventually            throw new IOException();        }        entry.key = readString(is);        entry.etag = readString(is);        if (entry.etag.equals("""")) {            entry.etag = null;        }        entry.serverDate = readLong(is);        entry.ttl = readLong(is);        entry.softTtl = readLong(is);        entry.responseHeaders = readStringStringMap(is);        return entry;    }    /**     * Creates a cache entry for the specified data.     */    public Entry toCacheEntry(byte[] data) {        Entry e = new Entry();        e.data = data;        e.etag = etag;        e.serverDate = serverDate;        e.ttl = ttl;        e.softTtl = softTtl;        e.responseHeaders = responseHeaders;        return e;    }    /**     * Writes the contents of this CacheHeader to the specified OutputStream.     */    public boolean writeHeader(OutputStream os) {        try {            writeInt(os CACHE_MAGIC);            writeString(os key);            writeString(os etag == null ? """" : etag);            writeLong(os serverDate);            writeLong(os ttl);            writeLong(os softTtl);            writeStringStringMap(responseHeaders os);            os.flush();            return true;        } catch (IOException e) {            VolleyLog.d(""%s"" e.toString());            return false;        }    }}private static class CountingInputStream extends FilterInputStream {    private int bytesRead = 0;    private CountingInputStream(InputStream in) {        super(in);    }    @Override    public int read() throws IOException {        int result = super.read();        if (result != -1) {            bytesRead++;        }        return result;    }    @Override    public int read(byte[] buffer int offset int count) throws IOException {        int result = super.read(buffer offset count);        if (result != -1) {            bytesRead += result;        }        return result;    }}/* * Homebrewed simple serialization system used for reading and writing cache * headers on disk. Once upon a time this used the standard Java * Object{InputOutput}Stream but the default implementation relies heavily * on reflection (even for standard types) and generates a ton of garbage. *//** * Simple wrapper around {@link InputStream#read()} that throws EOFException * instead of returning -1. */private static int read(InputStream is) throws IOException {    int b = is.read();    if (b == -1) {        throw new EOFException();    }    return b;}static void writeInt(OutputStream os int n) throws IOException {    os.write((n >> 0) & 0xff);    os.write((n >> 8) & 0xff);    os.write((n >> 16) & 0xff);    os.write((n >> 24) & 0xff);}static int readInt(InputStream is) throws IOException {    int n = 0;    n |= (read(is) << 0);    n |= (read(is) << 8);    n |= (read(is) << 16);    n |= (read(is) << 24);    return n;}static void writeLong(OutputStream os long n) throws IOException {    os.write((byte)(n >>> 0));    os.write((byte)(n >>> 8));    os.write((byte)(n >>> 16));    os.write((byte)(n >>> 24));    os.write((byte)(n >>> 32));    os.write((byte)(n >>> 40));    os.write((byte)(n >>> 48));    os.write((byte)(n >>> 56));}static long readLong(InputStream is) throws IOException {    long n = 0;    n |= ((read(is) & 0xFFL) << 0);    n |= ((read(is) & 0xFFL) << 8);    n |= ((read(is) & 0xFFL) << 16);    n |= ((read(is) & 0xFFL) << 24);    n |= ((read(is) & 0xFFL) << 32);    n |= ((read(is) & 0xFFL) << 40);    n |= ((read(is) & 0xFFL) << 48);    n |= ((read(is) & 0xFFL) << 56);    return n;}static void writeString(OutputStream os String s) throws IOException {    byte[] b = s.getBytes(""UTF-8"");    writeLong(os b.length);    os.write(b 0 b.length);}static String readString(InputStream is) throws IOException {    int n = (int) readLong(is);    byte[] b = streamToBytes(is n);    return new String(bUTF-8"");}static void writeStringStringMap(Map<String String> map OutputStream os) throws IOException {    if (map != null) {        writeInt(os map.size());        for (Map.Entry<String String> entry : map.entrySet()) {            writeString(os entry.getKey());            writeString(os entry.getValue());        }    } else {        writeInt(os 0);    }}static Map<String String> readStringStringMap(InputStream is) throws IOException {    int size = readInt(is);    Map<String String> result = (size == 0)            ? Collections.<String String>emptyMap()            : new HashMap<String String>(size);    for (int i = 0; i < size; i++) {        String key = readString(is).intern();        String value = readString(is).intern();        result.put(key value);    }    return result;}

这里面有几个方法的作用我不太理解,希望有大牛可以给解释一下,谢谢。
不明的方法是
static void writeInt(OutputStream os int n) throws IOException {
os.write((n >> 0) & 0xff);
os.write((n >> 8) & 0xff);
os.write((n >> 16) & 0xff);
os.write((n >> 24) & 0xff);
}

static int readInt(InputStream is) throws IOException {    int n = 0;    n |= (read(is) << 0);    n |= (read(is) << 8);    n |= (read(is) << 16);    n |= (read(is) << 24);    return n;}static void writeLong(OutputStream os long n) throws IOException {    os.write((byte)(n >>> 0));    os.write((byte)(n >>> 8));    os.write((byte)(n >>> 16));    os.write((byte)(n >>> 24));    os.write((byte)(n >>> 32));    os.write((byte)(n >>> 40));    os.write((byte)(n >>> 48));    os.write((byte)(n >>> 56));}static long readLong(InputStream is) throws IOException {    long n = 0;    n |= ((read(is) & 0xFFL) << 0);    n |= ((read(is) & 0xFFL) << 8);    n |= ((read(is) & 0xFFL) << 16);    n |= ((read(is) & 0xFFL) << 24);    n |= ((read(is) & 0xFFL) << 32);    n |= ((read(is) & 0xFFL) << 40);    n |= ((read(is) & 0xFFL) << 48);    n |= ((read(is) & 0xFFL) << 56);    return n;}

我不明白为什么需要作与或操作,为什么要左移右移,这是定好的计算方式???

解决方案

已解决,…………………………谢谢

时间: 2025-01-26 14:12:18

左移 右移 与 或-关于左移右移与或的作用的相关文章

C语言里的左移和右移运算

先说左移,左移就是把一个数的所有位都向左移动若干位,在C中用<<运算符.例如: int i = 1;i = i << 2; //把i里的值左移2位 也就是说,1的2进制是000...0001(这里1前面0的个数和int的位数有关,32位机器,gcc里有31个0),左移2位之后变成000...0100,也就是10进制的4,所以说左移1位相当于乘以2,那么左移n位就是乘以2的n次方了(有符号数不完全适用,因为左移有可能导致符号变化,下面解释原因) 需要注意的一个问题是int类型最左端的

关于左移和右移

一.文章来由 项目需要将一个int拆开成高16位和低15位存不同的id,形成一个新的id,所以~~~ 二.算术移位和逻辑移位 算术移位-有符号数的倍增.减半: 逻辑移位-无符号数的倍增.减半. 比如一个有符号位的8位二进制数11001101,逻辑右移就不管符号位,如果移一位就变成01100110.算术右移要管符号位,右移一位变成10100110. 左移 逻辑左移=算数左移,右边统一添0. 右移 (1)逻辑右移,左边统一添0(无符号) (2)算数右移,左边添加的数和符号有关(有符号) e.g:10

按位右移运算符 (&amp;gt;&amp;gt;)

运算   右移表达式的位,保持符号不变. result = expression1 >> expression2 参数 result 任何变量. expression1 任何表达式. expression2 任何表达式. 说明 >> 运算符把 expression1 的所有位向右移 expression2 指定的位数.expression1 的符号位被用来填充右移后左边空出来的位.向右移出的位被丢弃.例如,下面的代码被求值后,temp 的值是 -4:-14 (即二进制的 11110

无符号右移运算符 (&amp;gt;&amp;gt;&amp;gt;)

运算   右移表达式的位,不保留符号. result = expression1 >>> expression2 参数 result 任何变量. expression1 任何表达式. expression2 任何表达式. 说明 >>> 运算符把 expression1 的各个位向右移 expression2 指定的位数.右移后左边空出的位用零来填充.移出右边的位被丢弃.例如: var temptemp = -14 >>> 2 变量 temp 的值为 -

按位左移运算符 (&amp;lt;&amp;lt;)

运算   左移表达式的位. result = expression1 << expression2 参数 result 任何变量. expression1 任何表达式. expression2 任何表达式. 说明 << 运算符把 expression1 的所有位向左移 expression2 指定的位数.例如: var temptemp = 14 << 2 变量 temp 的值为 56,因为 14 (即二进制的 00001110)向左移两位等于 56 (即二进制的 00

javascript中负数算术右移、逻辑右移的奥秘探索_javascript技巧

javascript中负数的算术右移和逻辑右移都十分的让人迷惑,特别是逻辑右移>>>,你会发现即使一个很小的负数,右移之后,也会得到一个无比巨大的数,这是为什么呢? 原来在逻辑右移中符号位会随着整体一起往右移动,这样就是相当于无符号数的移动了,最后得到的就是一个正数,因为符号位不存在了.首先逻辑右移产生的一定是32位的数,然后负数的符号位为1,这意味着从第32位到符号位的位置全部由1填充,这样的数能不大吗例如-1,逻辑右移0位表现形式就是1111 1111 1111 1111 1111

DES算法中循环左移的问题

问题描述 DES算法中循环左移的问题 最近在学习DES算法,看到子密钥生成过程中要对28比特串循环左移:当i = 1,2,9,16时,移一位,对其他 i 则移两位.我想问为什么是对这4个移1位? 解决方案 C++循环左移问题海豚算法循环左移循环左移-海豚算法

CSS怎么将背景图左移/上移/右移10px

将背景图左移,对background定位属性使用比较熟悉的朋友应该很容易就可以做到,下面有个不错的示例,不会的朋友可以参考下   背影图片的左上角相对当前元素左上角的坐标. 右为X轴正半轴, 下为Y轴正半轴 当前元素左上角坐标为 0,0 默认图片的左上角正对当前元素的左上角 如果图片想向左移 10px; 复制代码 代码如下: background:url(images/hh.gif) no-repeat -10px 0;} 如果图片想向上移 10px; 复制代码 代码如下: background

ListBox实现上移,下移,左移,右移的简单实例

 这篇文章主要介绍了ListBox实现上移,下移,左移,右移的简单实例.需要的朋友可以过来参考下,希望对大家有所帮助    代码如下: <html> <head>     <title>Javascript版选择下拉菜单互移且排序</title>     <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </hea