在python中使用shift进行解码/恢复字符

时间:2018-04-24 00:42:00

标签: python bit-shift shift

我有一个功能。输入将是一个单词,并且每次将每个字符添加到结果的移位值。

def magic2(b):
res = 0
    for c in b:
       res = (res << 8) + ord(c)
       print(res)
return res

因为它使用轮班,我会丢失一些数据。我想用输入字的确切字母解码/反转它。

例如,如果输入为“saman”,则输出结果为“495555797358”,并且将逐步执行:

115
29537
7561581
1935764833
495555797358

如何使用这些输出返回输入字?

1 个答案:

答案 0 :(得分:1)

考虑一下你在做什么:对于每个字符,你向左移8位,然后加上另外8位。 1

那么,你如何撤消呢?好吧,对于每个字符,你抓住最右边的8位,然后将其他所有内容右移8位。你怎么知道什么时候完成的?当向右移动8位时,你得到0,你必须得到最左边的字符。所以:

// index.tsx
import * as React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, Switch } from 'react-router-dom';

import { Home } from './containers/home';
import { SMS } from './containers/sms';

import { history, store } from './store';

export const App = () => (
  <Provider store={store}>
    <Router basename="/" history={history}>
      <Switch>
        <Route exact path="/call" component={Home} />
        <Route exact path="/sms" component={SMS} />
      </Switch>
    </Router>
 </Provider>
);

// store.ts  
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createBrowserHistory, createHashHistory } from 'history';
import thunk from 'redux-thunk';

import { storage } from '../services/local-storage';
import { callsReducer } from './calls/reducer';

import { Call } from '../interfaces/call.interface';
import { CallMap } from '../interfaces/call-map.interface';

const STORAGE_NAME = 'SIP_CALL_SIMULATOR';

const {
  loadState,
  saveState,
} = storage({
  name: STORAGE_NAME,
  localStorage,
});

interface RootState {
  calls: CallMap;
}

const initialState: RootState = {
  calls: {},
};

const persistedState = loadState(initialState);
const reducer = combineReducers({
  calls: callsReducer,
  routing: routerReducer,
});

const store = createStore(reducer, persistedState, applyMiddleware(thunk));

// const browserHistory = createBrowserHistory();
const hashHistory = createHashHistory();
// const history = syncHistoryWithStore(browserHistory, store);
const history = syncHistoryWithStore(hashHistory, store);

store.subscribe(() => {
  console.log(`Updated the redux store.`);
  const state = store.getState();
  console.log(state);
  saveState(state);
});

export { history, store }; 

现在你只需弄清楚如何处理每个def unmagic2(n): while n > 0: c = chr(n & 0xff) # 0xff is (1 << 8) - 1 n = n >> 8 以获取原始字符串。它并不像你最初想象的那样相当,因为我们将最左边的字符放在最后,而不是第一个。但你应该能够从这里弄明白。

<子> 1。如果你正在使用Unicode的全部色域,这当然是有损的,因为你向左移8位然后加上另外21位,所以没有办法扭转它。但我假设您在这里使用Latin-1字符串,或c - 或Python 2 bytes